Search code examples
javadatetimedatetime-formatdata-conversiondatetimeformatter

Converting one date time format into another in Java


I have a situation where I need to convert one Java date time format into another but have been having just a bear of a time doing so. Been searching for solutions a long time and have tried many things that have just not worked but I'm at my wits end :(.

I have to convert from yyyy-MM-dd'T'HH:mm:ss to MM/dd/yyyy HH:mm:ss

This is the last thing I've tried, but alas it has no effect at all at transforming the pattern:

private Instant convertInstantFormat(Instant incomingDate) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(AUTH_DATE_PATTERN)
        .withZone(ZoneId.systemDefault());
    return Instant.parse(formatter.format(incomingDate));
}

Where

AUTH_DATE_PATTERN = "MM/dd/yyyy HH:mm:ss";

incomingDate = 2021-10-22T06:39:13Z and outgoing date = 2021-10-22T06:39:13Z

I'm sure this is probably just the most naive attempt. I've tried standardizing the date format and then reformatting, but no go.

I'm just sort of out of steam. As always, any and all help from this incredible community is tremendously appreciated!


UPDATE


I just wanted to point out that the input and output to this method are of type "Instant." Apologies for not making this clear initially.


Solution

  • I have to convert from yyyy-MM-dd'T'HH:mm:ss to MM/dd/yyyy HH:mm:ss

    Your incoming date time format is ISO_LOCAL_DATE_TIME.

    String datetime = "2021-12-16T16:22:34";
    LocalDateTime source = LocalDateTime.parse(datetime,DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    
    // desired output format
    String AUTH_DATE_PATTERN = "MM/dd/yyyy HH:mm:ss";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(AUTH_DATE_PATTERN);
    String output = source.format(formatter);
    System.out.println(output);
    

    prints

    12/16/2021 16:22:34
    

    If your incoming date is 2021-10-22T06:39:13Z that is a zoned date time and can be parsed-from/formatted-to using DateTimeFormatter.ISO_ZONED_DATE_TIME.