简体   繁体   中英

Unable to parse timestamp string to Calendar

I tried to convert this string "1593572400" (equivalent to GMT: Wednesday, 1 July 2020 03:00:00) to Calendar in Java. I tried parse in so many ways, but I'm always getting a java.text.parseException error.

What am I doing wrong?

Calendar date = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // tried many other formats

try {
    date.setTime(sdf.parse(date));
} catch (Exception ex) {
    ...    
}

I recommend you switch from the outdated and error-prone java.util date-time API to the rich set of modern date-time API .


    import java.text.ParseException;
    import java.time.Instant;
    
    public class Main {
        public static void main(final String[] args) throws ParseException {
            Instant instant = Instant.ofEpochSecond(1593572400);
            System.out.println(instant);
        }
    }

Output:

2020-07-01T03:00:00Z

Once you have an object of Instant , you can easily convert it to other date/time objects as shown below:

    import java.text.ParseException;
    import java.time.Instant;
    import java.time.LocalDateTime;
    import java.time.OffsetDateTime;
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    
    public class Main {
        public static void main(final String[] args) throws ParseException {
            Instant instant = Instant.ofEpochSecond(1593572400);
            System.out.println(instant);
    
            ZonedDateTime zdt = instant.atZone(ZoneId.of("Europe/London"));
            OffsetDateTime odt = zdt.toOffsetDateTime();
            LocalDateTime ldt = odt.toLocalDateTime();
            System.out.println(zdt);
            System.out.println(odt);
            System.out.println(ldt);
        }
    }

Output:

2020-07-01T03:00:00Z
2020-07-01T04:00+01:00[Europe/London]
2020-07-01T04:00+01:00
2020-07-01T04:00

Check this to get an overview of modern date-time classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM