Henry Ing-Simmons Henry Ing-Simmons - 1 year ago 81
Android Question

Get timestamp for start of day

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


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??

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download