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.

3
  • 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 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. Commented Dec 28, 2019 at 7:31
  • It’s a time zone issue. Which time zone are you in? Commented Dec 28, 2019 at 7:33
  • Does this answer your question? how to convert milliseconds to date format in android? I recommend the answer by Basil Bourque. Commented Dec 28, 2019 at 13:29

1 Answer 1

1

Try as follow

formatter.timeZone = TimeZone.getTimeZone("UTC")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.