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??
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.
1 Day: 86,400 seconds.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With