Format Instant to String



  • 3 Answer(s)

    Time Zone
    The Instant of time-zone format is required. Left out a time-zone,  does not know how to convert the instant to human date-time fields of the formatter, and therefore throws an exception.

    Formatter has can be added directly by using time-zone, the formatter using withZone() 

    DateTimeFormatter formatter =
        DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                         .withLocale( Locale.UK )
                         .withZone( ZoneId.systemDefault() );
    

     String Generating
    Presently use that formatter to develop the String representation of the Instant.

    Instant instant = Instant.now();
    String output = formatter.format( instant );
    

    Dump to console.

    System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
    System.out.println("instant: " + instant );
    System.out.println("output: " + output );
    

    This format has run by.

    formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
    instant: 2015-06-02T21:34:33.616Z
    output: 02/06/15 14:34
    
    Answered on December 20, 2018.
    Add Comment

    Use This Code:

    public static void main(String[] args) {
    
        DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .withZone(ZoneId.systemDefault());
    
        System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));
    
    }
    Answered on January 16, 2019.
    Add Comment

    You should set time zone to formatter and all will be fine, like this :

    Instant instant = Instant.ofEpochMilli(92554380000L);
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
    assert formatter.format(instant).equals("07/12/72 05:33");
    assert instant.toString().equals("1972-12-07T05:33:00Z");
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.