Get today midnight as milliseconds for given timezone java

Rajith K :

I need to get the today midnight time as milliseconds. For example, today's date is 2020-03-20 and I convert this today midnight as milliseconds using the below code. If it works fine in my local environment, but the problem is when I deploy this code to the server, the server has UTC time zone, So even I pass the timezone, the milliseconds returned is wrong. After debugging I found out that this is happening due to parsing the Date, the date uses the default timeZone. I tried to set the timeZone in the Date, but the millisecond value returning is wrong even the date is 2020/03/20 00:00:00. For you to understand more below are some cases.

In the local Environment: Time Zone pass to method = "Asia/Colombo"

Date in milliseconds = 1584642600000

Converted date = Fri Mar 20 2020 00:00:00

In the Server Environment: Time Zone pass to method = "Asia/Colombo"

Date in milliseconds = 1584662400000

Converted date = Fri Mar 20 2020 05:30:00

Note that here Time Zone is the value I pass to my method parameter. I'm using java 8.

    private static final String DATE_FORMAT = "yyyy/MM/dd 00:00:00";

    private long getTMT(String timeZone) {
        try {
            ZoneId zoneId = ZoneId.of(timeZone);
            ZonedDateTime currentZone = ZonedDateTime.now(zoneId);
            ZonedDateTime zonedDateTime =
                    currentZone.withZoneSameInstant(zoneId);
            DateTimeFormatter format =
                    DateTimeFormatter.ofPattern(DATE_FORMAT);
            String formattedDateTime = zonedDateTime.format(format);
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            Date date = sdf.parse(formattedDateTime);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

Hope I explained my question clearly, please let me know your answers/comments on this.

Thank you.

M. Prokhorov :

Formatting to string and then parsing from it is a horrible solution, especially since you also have to also construct all these parsers every time, and your format effectively has hacks in it.

There are simpler ways to both construct a midnight ZDT:

ZonedDateTime zdt = LocalDate.now(zoneId).atTime(LocalTime.MIDNIGHT).atZone(zoneID);

And then extracting the epoch-millis value from it:

long epoch = zdt.toInstant().toEpochMilli();

Alternatively, since you know that milliseconds and nanoseconds are always 0 at midnight, this is marginally faster:

long epoch = zdt.toEpochSecond() * 1000;

The second approach wouldn't work if your time is arbitrary, as it will always ignore milli-of-second value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334394&siteId=1