Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get timestamp for start of day

Tags:

android

I am storing times/dates in a database using a unix timestamp. I want to then get all the instances on certain day so I therefore need to calculate the timestamp for the start of the day in order to query the database.

I have done a similar thing in php by passing mktime the values for the day/month/year from a date object and setting hour and minute to zero. There doesn't seem to be similar functions for this in java/android (the functions for getting the specific parts of date are deprecated)

Can anyone give some guidance on this? Thanks

Edit:

Ok so I realised this might work:

public static int startOfDay(Timestamp time) {
        Calendar cal = dateToCalendar(new Date(time.getTime()));
        cal.add(Calendar.HOUR_OF_DAY, -Calendar.HOUR_OF_DAY);
        cal.add(Calendar.MINUTE, -Calendar.MINUTE);
        cal.add(Calendar.SECOND, -Calendar.SECOND);
        Log.i("Time", cal.getTime().toString());        
        return (int) cal.getTimeInMillis()/1000;
}

However when I ran this just now I got:

Sat Dec 15 01:24:00 GMT 2012

The seconds are right but the hour and minute are wrong??

like image 800
Henry Ing-Simmons Avatar asked Dec 15 '12 12:12

Henry Ing-Simmons


People also ask

How do you calculate a timestamp?

If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

How much is a day in timestamp?

1 Day: 86,400 seconds.


1 Answers

When dealing with time, you should always consider time zones. You database timestamps should be always stored in one time zone (e.g. UTC). Your computation should then consider that users can be in different time zones and that they can change time zones.

If you want to compute start of the day in the time zone the user has currently set in his phone. Create the Calendar instance with:

Calendar cal = Calendar.getInstance(); 

To get the instance for a specific time zone use:

// use UTC time zone
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

Then set the beginning of the day:

cal.setTime(time); // compute start of the day for the timestamp
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
like image 136
Tomik Avatar answered Oct 16 '22 18:10

Tomik