I am writing an app which has a DatePicker
and a TimePicker
in the UI. I need to get the date and time set by the user and store in the server.
For example user chose "13 Nov 2015 13:00", and the timezone of my emulator is set as GMT+8, the returned timeInSec
in GMT independent of time zone should be "1447390800", but it turns out to be "1447387200", a difference of 1 hour. End up my displayed time received from server also wrong.
Why is it so? Something to do with daylight savings in GMT timezone countries or what have I done wrongly in the code? In my country there is no daylight savings..
Here is my code:
Calendar cal = Calendar.getInstance();
cal.set(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth(), mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute(), 0);
// get time in seconds independent of timezone <- update on 2015/11/14: this is wrong!!
long timezoneOffset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
long timeInSec = ((cal.getTimeInMillis() + timezoneOffset)/1000);
Update
After checking through the code again, you found it is my TimePicker giving the wrong value.
If you want the UTC timestamp you can directly use
getTimeInMillis()
For example set the calendar date to
13 Nov 2015 13:00
with a GMT+8 timezone:the value of
timeInSec
is1447390800
EDIT
What is the output you obtain with this snippet of code?
This is the result I obtained:
(Posted on behalf of the question author).
The problem was because of the TimePicker.
Calendar.currentTimeMillis()
actually gives time independent of timezone (i.e. UTC). This link (Java: Timezone why different timezone give same value in millisec) is so misleading! This should be what you should be looking at: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getTimeInMillis()So I should be just doing this: