How to parse/format dates with LocalDateTime? (Java 8)

后端 未结 7 1226
既然无缘
既然无缘 2020-11-22 01:11

Java 8 added a new java.time API for working with dates and times (JSR 310).

I have date and time as string (e.g. \"2014-04-08 12:30\"). How can I obtai

相关标签:
7条回答
  • 2020-11-22 01:47

    Let's take two questions, example string "2014-04-08 12:30"

    How can I obtain a LocalDateTime instance from the given string?

    import java.time.format.DateTimeFormatter
    import java.time.LocalDateTime
    
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
    
    // Parsing or conversion
    final LocalDateTime dt = LocalDateTime.parse("2014-04-08 12:30", formatter)
    

    dt should allow you to all date-time related operations

    How can I then convert the LocalDateTime instance back to a string with the same format?

    final String date = dt.format(formatter)
    
    0 讨论(0)
  • 2020-11-22 02:03

    Parsing date and time

    To create a LocalDateTime object from a string you can use the static LocalDateTime.parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.

    String str = "1986-04-08 12:30";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    

    Formatting date and time

    To create a formatted string out a LocalDateTime object you can use the format() method.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
    String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"
    

    Note that there are some commonly used date/time formats predefined as constants in DateTimeFormatter. For example: Using DateTimeFormatter.ISO_DATE_TIME to format the LocalDateTime instance from above would result in the string "1986-04-08T12:30:00".

    The parse() and format() methods are available for all date/time related objects (e.g. LocalDate or ZonedDateTime)

    0 讨论(0)
  • 2020-11-22 02:03

    GET CURRENT UTC TIME IN REQUIRED FORMAT

    // Current UTC time
            OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
    
            // GET LocalDateTime 
            LocalDateTime localDateTime = utc.toLocalDateTime();
            System.out.println("*************" + localDateTime);
    
            // formated UTC time
            DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            System.out.println(" formats as " + dTF.format(localDateTime));
    
            //GET UTC time for current date
            Date now= new Date();
            LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
            DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
    
    0 讨论(0)
  • 2020-11-22 02:05

    You can also use LocalDate.parse() or LocalDateTime.parse() on a String without providing it with a pattern, if the String is in ISO-8601 format.

    for example,

    String strDate = "2015-08-04";
    LocalDate aLD = LocalDate.parse(strDate);
    System.out.println("Date: " + aLD);
    
    String strDatewithTime = "2015-08-04T10:11:30";
    LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
    System.out.println("Date with Time: " + aLDT);
    

    Output,

    Date: 2015-08-04
    Date with Time: 2015-08-04T10:11:30
    

    and use DateTimeFormatter only if you have to deal with other date patterns.

    For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:

    DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
    String anotherDate = "04 Aug 2015";
    LocalDate lds = LocalDate.parse(anotherDate, dTF);
    System.out.println(anotherDate + " parses to " + lds);
    

    Output

    04 Aug 2015 parses to 2015-08-04
    

    also remember that the DateTimeFormatter object is bidirectional; it can both parse input and format output.

    String strDate = "2015-08-04";
    LocalDate aLD = LocalDate.parse(strDate);
    DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
    System.out.println(aLD + " formats as " + dTF.format(aLD));
    

    Output

    2015-08-04 formats as 04 Aug 2015
    

    (see complete list of Patterns for Formatting and Parsing DateFormatter)

      Symbol  Meaning                     Presentation      Examples
      ------  -------                     ------------      -------
       G       era                         text              AD; Anno Domini; A
       u       year                        year              2004; 04
       y       year-of-era                 year              2004; 04
       D       day-of-year                 number            189
       M/L     month-of-year               number/text       7; 07; Jul; July; J
       d       day-of-month                number            10
    
       Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
       Y       week-based-year             year              1996; 96
       w       week-of-week-based-year     number            27
       W       week-of-month               number            4
       E       day-of-week                 text              Tue; Tuesday; T
       e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
       F       week-of-month               number            3
    
       a       am-pm-of-day                text              PM
       h       clock-hour-of-am-pm (1-12)  number            12
       K       hour-of-am-pm (0-11)        number            0
       k       clock-hour-of-am-pm (1-24)  number            0
    
       H       hour-of-day (0-23)          number            0
       m       minute-of-hour              number            30
       s       second-of-minute            number            55
       S       fraction-of-second          fraction          978
       A       milli-of-day                number            1234
       n       nano-of-second              number            987654321
       N       nano-of-day                 number            1234000000
    
       V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
       z       time-zone name              zone-name         Pacific Standard Time; PST
       O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
       X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
       x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
       Z       zone-offset                 offset-Z          +0000; -0800; -08:00;
    
       p       pad next                    pad modifier      1
    
       '       escape for text             delimiter
       ''      single quote                literal           '
       [       optional section start
       ]       optional section end
       #       reserved for future use
       {       reserved for future use
       }       reserved for future use
    
    0 讨论(0)
  • 2020-11-22 02:05

    Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply DateTimeFormatter since LocalDateTime is already prepared for it:

    Convert LocalDateTime to Time Zone ISO8601 String

    LocalDateTime ldt = LocalDateTime.now(); 
    ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
    String iso8601 = zdt.toString();
    

    Convert from ISO8601 String back to a LocalDateTime

    String iso8601 = "2016-02-14T18:32:04.150Z";
    ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
    LocalDateTime ldt = zdt.toLocalDateTime();
    
    0 讨论(0)
  • 2020-11-22 02:09

    I found the it wonderful to cover multiple variants of date time format like this:

    final DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
    dtfb.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS"))
        .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
        .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS"))
        .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"))
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0);
    
    0 讨论(0)
提交回复
热议问题