0

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • It’s scaringly easy to get confused about `java.util.Calendar`. And `SimpleDateFormat` is even worse. Consider throwing away those long outmoded and poorly designed classes, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 28 '19 at 07:31
  • It’s a time zone issue. Which time zone are you in? – Ole V.V. Dec 28 '19 at 07:33
  • Does this answer your question? [how to convert milliseconds to date format in android?](https://stackoverflow.com/questions/7953725/how-to-convert-milliseconds-to-date-format-in-android) I recommend [the answer by Basil Bourque](https://stackoverflow.com/a/49378569/5772882). – Ole V.V. Dec 28 '19 at 13:29

1 Answers1

1

Try as follow

formatter.timeZone = TimeZone.getTimeZone("UTC")
Abner Escócio
  • 2,697
  • 2
  • 17
  • 36