0

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) {
    ...    
}
aseolin
  • 1,184
  • 3
  • 17
  • 35
  • I think it might be helpful if add the entire stack trace for the exception in your question – Jocke Jul 01 '20 at 15:29
  • 2
    Does this answer your question? [Java: Date from unix timestamp](https://stackoverflow.com/questions/3371326/java-date-from-unix-timestamp). In particular, note the comments relating to `java.time` - which should be used in preference to classes such as `Date`. – andrewJames Jul 01 '20 at 15:40
  • 1
    The terrible `Calendar` class is obsolete, legacy, supplanted years ago by the modern *java.time* classes defined in JSR 310. – Basil Bourque Jul 01 '20 at 15:43

1 Answers1

4

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.

Dmitry Pisklov
  • 1,196
  • 1
  • 6
  • 16
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110