我有一个形式的字符串" mm / yyyy"我想将它与本地系统的日期进行比较。
我想过要在我的月份和日历中的MONTH字段之间使用转换表,例如:
Calendar cal = Calendar.getInstance();
String date = "07/2014";
String month = date.subString(0, 2);
int monthToCompare;
if (month.equals("01"))
monthToCompare = cal.JANUARY;
if (month.equals("02"))
monthToCompare = cal.FEBRUARY;
...
然后手动比较if。我不喜欢它,因为我觉得这么简单的操作太长了。
我想到的另一个选项是获取当前Date()
并使用before()
方法。这意味着将我的日期转换为日期格式,但是不推荐使用简单的方法,我必须指定毫秒数,我不知道如何轻松地做到这一点(考虑到闰年,日历更正等等)自1970年以来。)
答案 0 :(得分:32)
使用@Mifmif回答我终于解决了问题:
if (new SimpleDateFormat("MM/yyyy").parse(date).before(new Date())) {
...
}
答案 1 :(得分:6)
试试这个:
new SimpleDateFormat("MM/yyyy").parse("07/2014").compareTo(new Date());
答案 2 :(得分:3)
YearMonth.parse(
"07/2014" ,
DateTimeFormatter.ofPattern( "MM/uuuu" )
).isAfter(
YearMonth.now(
ZoneId.of( "Africa/Tunis" )
)
)
现代解决方案使用 java.time 类而不是麻烦的旧日期时间类。
要表示整月,请使用YearMonth
课程。
String input = "07/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" ) ;
YearMonth ym = YearMonth.parse( input , f ) ;
提示:在整个代码库中使用此类YearMonth
对象,而不仅仅是字符串。当做需要字符串来交换数据时,请使用标准ISO 8601格式:YYYY-MM
。在解析/生成字符串时,java.time类默认使用标准格式,因此无需定义格式化模式。
确定当前年月意味着确定当前日期。
时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。
如果未指定时区,则JVM会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好明确指定您期望/预期的时区作为参数。
以continent/region
的格式指定proper time zone name,例如America/Montreal
,Africa/Casablanca
或Pacific/Auckland
。切勿使用诸如EST
或IST
之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
如果要使用JVM的当前默认时区,请求它并作为参数传递。如果省略,则隐式应用JVM的当前默认值。最好是明确的,因为默认情况下可以在运行时期间由JVM中任何应用程序的任何线程中的任何代码随时更改。
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
同样的想法适用于获取当前YearMonth
:传递ZoneId
。
YearMonth currentYearMonth = YearMonth.now( z ) ;
使用方法isBefore
,isAfter
和equals
进行比较。
boolean isAfterCurrentYearMonth = ym.isAfter( currentYearMonth ) ;
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和& SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。
答案 3 :(得分:1)
//getting current date
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
//compare the dates
Date date1 = new Date("second_date to be compared");
Date date2 = new Date(getDateTime());
if(date1.before(date2)) {
Log.d("Date already passed", " " + "second_date");
}