Search code examples
androiddatecalendarjava.util.calendar

Getting confused with java.util.Calendar


I want to get the date of SMS in format dd-MM-yyyy and time in format HH:MM (in 24hr format) on which it was received on phone. I use the following code

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(messages[0].getTimestampMillis());
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
String finalDateString = formatter.format(calendar.getTime());
Log.i(TAG, "Date new Format " + finalDateString);

Message was recieved on 11:50PM on 26-Dec-19 at phone, but I get the result in Log "Date new Format 27/12/2019 10:50:03.000". Please notice instead of 26 its giving 27 and time is also 1 hr less, instead of 11 its 10. Is this a normal behaviour? Do I have to subtract 1 day from date to get correct data and add 1 hr in time? Will this always work correctly? Do I have to specify timezone to get correct data? Please advise as I got confused with ths.


Solution

  • Try as follow

    formatter.timeZone = TimeZone.getTimeZone("UTC")