SimpleDateFormatter.parse giving output in different format than specified

Don’t pass dates as strings to your MySQL database. It’s better, both easier and safer to pass date objects. For one thing, it relieves you of formatting and any formatting issues. Best, pass instances of a class from java.time, the modern Java date and time API. In your case a LocalDateTime will do.

    String ep ="a1527069600";
    long epoch = Long.parseLong(ep.substring(1));
    Instant inst = Instant.ofEpochSecond(epoch);
    LocalDateTime ldt = inst.atZone(ZoneId.of("Asia/Calcutta")).toLocalDateTime();

    System.out.println(ldt);

    PreparedStatement ps = myDatabaseConnection.prepareStatement(
            "insert into my_table (my_date_time) values (?)");
    ps.setObject(1, ldt);

The LocalDateTime obtained is:

2018-05-23T15:30

I simplified your conversion from epoch string a bit. Use a primitive, lowercase long rather than a Long object. I am using your time zone, Asia/Calcutta, assuming that your database values are in this time zone. Normal recommendations are to keep database values in UTC, at least if there’s any possibility that the data will ever be used outside your time zone. If you want this, use this conversion instead of the one above:

    LocalDateTime ldt = inst.atOffset(ZoneOffset.UTC).toLocalDateTime();

Link: Oracle tutorial: Date Time explaining how to use java.time.

Leave a Comment