Home > Back-end >  Get Epoch/ Unix timestamp from Zoned Datetime in Java
Get Epoch/ Unix timestamp from Zoned Datetime in Java

Time:11-14

I have to convert the birth date of people born in USA to Epoch and store it in database. Right now I am getting birth date from a legacy system in two different formats: yyyy-MM-dd HH:mm:ss & dd-MMM-yyyy.

How do I convert it properly with taking into account zone offset? My current code looks like this but it is having problems due to zone offset. What is proper way to go about this?

public class DateTimeUtils
{
    public static Instant parseBirthDateTime(String birthdate)
    {

        if (birthdate != null)
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
            Date date;

            try
            {
                date = formatter.parse(birthdate);
            }
            catch (Exception e)
            {
                if (!e.getMessage().contains("Unparseable date"))
                {
                    if (Logger.isErrorEnabled())
                        Logger.error(e);
                }
                formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);

                try
                {
                    date = formatter.parse(birthdate);
                }
                catch (Exception ex)
                {
                    if (Logger.isErrorEnabled())
                        Logger.error(e);
                    return Instant.parse("0001-01-01T00:00:00.00Z");
                }
            }

            if (date != null)
            {
                return Instant.ofEpochMilli(date.getTime());
            }
            else
            {
                return Instant.parse("0001-01-01T00:00:00.00Z");
            }
        }

        return Instant.parse("0001-01-01T00:00:00.00Z");
    }

}

CodePudding user response:

In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.

You need time-zone for each date-time value you are getting to convert them to an Instant from which you get the Epoch value.

Using the DateTimeFormatterBuilder, you can create a DateTimeFormatter with the default value for time as 00:00 and then use the same formatter to parse date as well as date-time into the LocalDateTime.

Demo:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("[dd-MMM-uuuu[ HH:mm]][uuuu-MM-dd HH:mm:ss]")
                .parseCaseInsensitive()
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .toFormatter(Locale.ENGLISH);

        String arr[] = {"2022-11-14 08:40:50", "14-Nov-2022"};
        for (String sdt : arr) {
            LocalDateTime ldt = LocalDateTime.parse(sdt, formatter);
   
            // Assuming you have the time-zone for each value. For the demo, I
            // have used here only one time-zone.
            ZoneId zodeId = ZoneId.of("America/New_York");
            long epoch = ldt.atZone(zodeId).toInstant().toEpochMilli();
            System.out.println(epoch);
        }
    }
}

Output:

1668433250000
1668402000000

Learn more about the modern Date-Time API from Trail: Date Time.

  • Related