How can I parse UTC date/time (String) into something more readable?

前端 未结 10 873
深忆病人
深忆病人 2020-12-13 04:07

I have a String of a date and time like this: 2011-04-15T20:08:18Z. I don\'t know much about date/time formats, but I think, and correct me if I\'m wrong, that\

10条回答
  •  Happy的楠姐
    2020-12-13 04:45

    Already has lot of answer but just wanted to update with java 8 in case any one faced issues while parsing string date.

    Generally we face two problems with dates

    1. Parsing String to Date
    2. Display Date in desired string format

    DateTimeFormatter class in Java 8 can be used for both of these purpose. Below methods try to provide solution to these issues.

    Method 1: Convert your UTC string to Instant. Using Instant you can create Date for any time-zone by providing time-zone string and use DateTimeFormatter to format date for display as you wish.

    String dateString = "2016-07-13T18:08:50.118Z";
    String tz = "America/Mexico_City";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
    ZoneId zoneId = ZoneId.of(tz);
    
    Instant instant = Instant.parse(dateString);
    
    ZonedDateTime dateTimeInTz =ZonedDateTime.ofInstant(instant, zoneId);
    
    System.out.println(dateTimeInTz.format(dtf));
    

    Method 2:

    Use DateTimeFormatter built in constants e.g ISO_INSTANT to parse string to LocalDate. ISO_INSTANT can parse dates of pattern

    yyyy-MM-dd'T'HH:mm:ssX e.g '2011-12-03T10:15:30Z'

    LocalDate parsedDate
      = LocalDate.parse(dateString, DateTimeFormatter.ISO_INSTANT);
    
    DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy MM dd");
    System.out.println(parsedDate.format(displayFormatter));
    

    Method 3:

    If your date string has much precision of time e.g it captures fraction of seconds as well as in this case 2016-07-13T18:08:50.118Z then method 1 will work but method 2 will not work. If you try to parse it will throw DateTimeException Since ISO_INSTANT formatter will not be able to parse fraction of seconds as you can see from its pattern. In this case you will have to create a custom DateTimeFormatter by providing date pattern as below.

    LocalDate localDate 
    = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
    

    Taken from a blog link written by me.

提交回复
热议问题