2月29日的SimpleDateFormat分析日期错误 [英] SimpleDateFormat parse in wrong date for 29 February

查看:0
本文介绍了2月29日的SimpleDateFormat分析日期错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经连接好了

   public static boolean isFirstDayOfMonth(String format, String value) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date date = null;
    try {
        date = sdf.parse(value);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
    return dayOfMonth == 1;
   }

测试并返回True:

    boolean actual = CommonUtil.isFirstDayOfMonth("yyyy-MM-dd", "2021-02-29");
    assertTrue(actual);

I Found Out SimpleDateFormat将日期转换为2021年3月1日,尽管2021年没有2月29日。如果我在2021-02-30中通过,这是无效的,但它返回正确的结果。

推荐答案

tl;dr

java.time.LocalDate.parse( "2021-02-29" )
…
catch ( DateTimeParseException e )  // Thrown for invalid inputs

java.time

您正在使用几年前被JSR 310中定义的java.time类取代的可怕的日期-时间类。

默认情况下,java.time.LocalDate类拒绝解析无效输入。分析异常的陷阱。

    try {
        LocalDate ld = LocalDate.parse( "2021-02-29" ) ;
        System.out.println( ld ) ;
    } catch ( DateTimeParseException e ) {
        // … handle invalid input
        System.out.println( "Faulty input" ) ;
    }

查看此code run live at IdeOne.com


关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期-时间类,如java.util.DateCalendar、&;SimpleDateFormat

要了解更多信息,请参阅Oracle Tutorial。和搜索堆栈溢出以获取许多示例和解释。规范为JSR 310

Joda-Time项目现在位于maintenance mode中,建议迁移到java.time类。

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC driver。不需要字符串,也不需要java.sql.*类。Hibernate 5&;JPA 2.2支持java.time

从哪里获取java.time类?

这篇关于2月29日的SimpleDateFormat分析日期错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆