2016-05-30 69 views
1

我有一种方法只能在特定年份之前处理字符串。不过,我似乎无法让这个事情发挥作用 - 我不认为这个比较是正确的。有人可以告诉我如何比较几年内完成。如果Joda time是可以更好地还展示了如何(而不是告诉我只使用约达时间)如何在特定年份之前创建条件语句

的字符串是在英国的日期格式如16/02/2006

我的代码:

DateFormat df = new SimpleDateFormat("yyyy"); 
Date yearOnReport = df.parse(startDateString); 
Date threshold = df.parse("2006") 
if (yearOnReport<threshold){ 
...\\Do some stuff 
} 
+0

门槛不正确的单词我认为,因为门槛是包容性的,如<=。因为它是独一无二的,所以请使用tooLate。 –

+0

您使用的是Java 8吗?如果是这样,你应该使用从Joda派生的'java.time'类。 –

回答

3

在Java 8,使用LocalDateDateTimeFormatter

String startDateString = "16/02/2006"; 

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu"); 
LocalDate localDate = LocalDate.parse(startDateString, dateTimeFormatter); 
if (localDate.getYear() < 2006) { 
    // code here 
} 

如果您需要支持旧版本的Java,使用CalendarSimpleDateFormat

String startDateString = "16/02/2006"; 

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
Date date = simpleDateFormat.parse(startDateString); 
Calendar calendar = Calendar.getInstance(); 
calendar.setTime(date); 
if (calendar.get(Calendar.YEAR) < 2006) { 
    // code here 
} 

在Java 7,您可以通过从ThreeTen project获得新java.time API的反向移植做了Java 8路。
优势:当更高版本升级到Java 8,不需要在Java 8需要一个额外的库

或者代码将工作,增加Joda-Time并使用其LocalDateDateTimeFormat

String startDateString = "16/02/2006"; 

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy"); 
LocalDate localDate = formatter.parseLocalDate(startDateString); 
if (localDate.getYear() < 2006) { 
    // code here 
} 
+0

太好了。这很有用 –

0

你不能将日期与关系运算符进行比较。可以使用Date#compareTo方法。

+0

if(yearOnReport.before(threshold)){} –

+0

你也可以使用该方法。 –

0

使用before()逻辑运算符只适用于基元类型。

此:

DateFormat df = new SimpleDateFormat("yyyy"); 
Date yearOnReport = df.parse(startDateString); 
Date threshold = df.parse("2006") 
if (yearOnReport<threshold){ 
...\\Do some stuff 
} 

应该是这样的:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
Date yearOnReport = df.parse(startDateString); 
Date threshold = df.parse("2006") 
if (yearOnReport.before(threshold)){ 
...\\Do some stuff 
} 
+0

除非OP使用Java 8,否则应使用由Joda派生/启发的内建'java.time'类。 –

+0

解析错误,因为*“该字符串是英国日期格式,例如'16/02/2006'”*。 – Andreas