Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting datetime to string, wrong hours

I am doing like this in my android app (java):

String sdt_ = DateFormat.format("yyyyMMdd  HH:mm", dt_).toString();

but I got this

01-16 14:31:13.308: D/ThS(25810): dt_ = Wed Jan 16 13:28:00 GMT+00:00 2013
01-16 14:31:23.758: D/ThS(25810): sdt_ = 20130116  HH:28

if I change HH to hh I will get this

sdt_ = 20130116  01:28

but I need this

sdt_ = 20130116  13:28
like image 512
Foenix Avatar asked Jan 16 '13 14:01

Foenix


3 Answers

i don't know, what is wrong with your code, but this code works for me:

DateFormat df = new SimpleDateFormat("yyyyMMdd  HH:mm");
String sdt = df.format(new Date(System.currentTimeMillis()));
System.out.println(sdt);

EDIT:

later I found out that your original code should work with this:

String sdt_ = DateFormat.format("yyyyMMdd  kk:mm", dt_).toString();

apparently, android.text.format.DateFormat doesn't use 'H' constraint and uses 'k' instead of it! see this question for more details: How to set 24-hours format for date on java?

like image 106
Berťák Avatar answered Oct 12 '22 22:10

Berťák


This will do it for you:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd  HH:mm", Locale.getDefault());
String sdt_ = sdf.format(dt_);
like image 39
jenzz Avatar answered Oct 12 '22 21:10

jenzz


You used hh in your SimpleDateFormat pattern. Thats the 12 hour format. Use kk instead, that gives you the hours of the day in a 24 hour format.See SimpleDateFormat

like image 38
K_Anas Avatar answered Oct 12 '22 23:10

K_Anas