Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove Hour, Minute, and Second from Epoch timestamp

I need to write a function that accepts a java.util.Date and removes the hours, minutes, and milliseconds from it USING JUST MATH (no Date formatters, no Calendar objects, etc.):

private Date getJustDateFrom(Date d) {
    //remove hours, minutes, and seconds, then return the date
}

The purpose of this method is to get the date from a millisecond value, without the time.

Here's what I have so far:

private Date getJustDateFrom(Date d) {
    long milliseconds = d.getTime();
    return new Date(milliseconds - (milliseconds%(1000*60*60)));
}

The problem is, this only removes minutes and seconds. I don't know how to remove hours.

If I do milliseconds - (milliseconds%(1000*60*60*23)), then it goes back to 23:00 hrs on the previous day.

EDIT:

Here's an alternative solution:

public static Date getJustDateFrom(Date d) {
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    return c.getTime();
}

Will this solution be affected by time zone differences between the client/server sides of my app?

like image 353
Churro Avatar asked Dec 05 '22 09:12

Churro


2 Answers

There are 24 hours in a day. Use milliseconds%(1000*60*60*24).

like image 191
Mark Bailey Avatar answered Jan 07 '23 11:01

Mark Bailey


Simply not possible by your definition.

A millisecond timestamp represents milliseconds elapsed from a fixed point in time (1970-01-01 00:00:00.000 UTC, if I remember correctly). This timestamp can not be converted into a date + time without specifying the timezone to convert to.

So you can only round the timestamp to full days in respect to a specific timezone, not in general. So any fiddling with Date.getTime() and not taking into account any timezone is guaranteed to work in only one time zone - the one you hardcoded for.

Do yourself a favor and use a Calendar.

like image 30
Durandal Avatar answered Jan 07 '23 10:01

Durandal