Calendar date to yyyy-MM-dd format in java

后端 未结 9 912
别跟我提以往
别跟我提以往 2020-11-22 06:16

How to convert calendar date to yyyy-MM-dd format.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();          


        
9条回答
  •  盖世英雄少女心
    2020-11-22 06:38

    java.time

    The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.

    When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30

    ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
    ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
    
    DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
    String output = formatterOutput.format( zonedDateTime );
    

    Dump to console…

    System.out.println( "zonedDateTime: " + zonedDateTime );
    System.out.println( "output: " + output );
    

    When run…

    zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
    output: 2014-02-25
    

    Joda-Time

    Similar code using the Joda-Time library, the precursor to java.time.

    DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
    DateTime dateTime = DateTime.now( zone );
    DateTimeFormatter formatter = ISODateTimeFormat.date();
    String output = formatter.print( dateTime );
    

    ISO 8601

    By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.

    Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.

提交回复
热议问题