Search code examples
javatimestampjava-timedatetime-parsingzoneddatetime

How to convert Timestamp in CDT Format to MM/DD in Java?


I have a timestamp in cdt format as below "2023-06-05T09:00:01CDT", I want to convert this timestamp into MM/DD format in Java.

I have tried below : The expected output was: 6/5 But was getting parsing error.

ZonedDateTime ztime = ZonedDateTime.parse("2023-06-05T09:00:01CDT");
Date date = Date.from(Instant.from(ztime));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE);

Stack trace:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2023-06-05T09:00:01CDT' could not be parsed at index 19
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2056)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1958)
    at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:600)
    at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:585)
    at MyClass.main(MyClass.java:9)

Solution

  • Try this code snippet, if it is a parsing issue you can add a DateTimeFormatter :: documentation

        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz");
        ZonedDateTime time = ZonedDateTime.parse("2023-06-05T09:00:01CDT", format);
        Date date = Date.from(Instant.from(time));
        cal.setTime(date);
        Calendar cal = Calendar.getInstance();
        String date =  (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE);