tags:

views:

64

answers:

2

Hi,

I have a question about working with time in java, more specificly in Android.

I am developing a device that needs to check to see if an update with a remote server has been done today. I do this by comparing the time (in milliseconds) at midnight last night/this morning with the current time in milliseconds..

so my code is as follows:

Calendar now = Calendar.getInstance();  
long milliseconds = now.getTimeInMillis();  
long since_midnight = milliseconds%(86400000);  
long checkpoint = (milliseconds - since_midnight); 

however when I convert the checkpoint variable to date using:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");  
last_logged_text=formatter.format(checkpoint);

I get a time represention corresponding to 1 am this morning.

I realise that this has something to do with daylight savings time but Im unsure how to work around it.

Any help greatly appreciated.

Thanks

Kev

A: 

This resource may be useful.

Chathuranga Chandrasekara
+1  A: 

Its because the epoch and now have different timezones, effectively, thanks to DST, as you state.

A far better way to do what you want is to get 'now', lop off the time part, leaving you with midnight last night.

Calendar midnight = Calendar.getInstance ();

midnight.set (Calendar.HOUR_OF_DAY, 0);
midnight.set (Calendar.MINUTE, 0);
midnight.set (Calendar.SECOND, 0);
midnight.set (Calendar.MILLISECOND, 0);

long millisSinceMidnight = System.currentTimeMillis() - midnight.getTimeInMillis();
Visage
@Visage. Thanks, exactly what I was looking for.
Kevin Bradshaw