20年后的解析日期

时间:2015-11-04 11:21:48

标签: java

我有一个类似" 1512"的字符串。我需要将它转换为日期2015-12-31 23:59:59。

在这种情况下,我正在使用Java Dateformat解析。

我的代码:

json

它可以给出最多20年的日期。当日期是" 3610"时,它给出了1936年而不是2036年(当前世纪)。

3 个答案:

答案 0 :(得分:2)

我认为,您可以手动解析String,然后创建Date对象。

假设:

public static void checkDate(String date) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    int year = Integer.parseInt(date.substring(0, 2));
    int month = Integer.parseInt(date.substring(2, 4));
    calendar.setLenient(false);         
    int yearOfCentury = calendar.get(Calendar.YEAR);
    int century = yearOfCentury - yearOfCentury % 100;
    year = year + century;
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month-1);
    calendar.set(Calendar.DATE,             calendar.getActualMaximum(Calendar.DATE));
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE,  59);
    calendar.set(Calendar.SECOND,  59);
    System.out.println("Date +" + calendar.getTime());    
}

答案 1 :(得分:1)

如果您确定年份应始终为2000+,则手动将字符串前缀为“20”并使用SimpleDateFormat作为

private static final dateformat = new SimpleDateFormat("yyyyMM");

来自docs

  

使用缩写的年份模式(“y”或“yy”)进行解析,   SimpleDateFormat必须解释相对于某些的缩写年份   世纪。它通过将日期调整到80年之前来实现   并且在创建SimpleDateFormat实例之后20年。   例如,使用“MM / dd / yy”模式和SimpleDateFormat   在1997年1月1日创建的实例,字符串“01/11/12”将是   解释为2012年1月11日,而字符串“05/04/64”将是   解释为5月4日, 1964

答案 2 :(得分:0)

Java 8中YearMonth解析器的2位数年份的默认行为是从2000开始。这样就可以得到你期望的结果:

YearMonth ym = YearMonth.parse("3610", DateTimeFormatter.ofPattern("yyMM"));
//ym = 2036-10

如果你想要在特定日期截止(比如你希望80-99为1980-1999,0-79为2000-2079),你可以使用a custom pattern