6

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
dymmeh
  • 22,247
  • 5
  • 53
  • 60
Foenix
  • 991
  • 3
  • 10
  • 23

3 Answers3

8

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?

Community
  • 1
  • 1
Berťák
  • 7,143
  • 2
  • 29
  • 38
4

This will do it for you:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd  HH:mm", Locale.getDefault());
String sdt_ = sdf.format(dt_);
jenzz
  • 7,239
  • 6
  • 49
  • 69
  • thank you, it is working (with or without Locale.getDefault()) – Foenix Jan 16 '13 at 15:19
  • 1
    It does work without `Locale.getDefault()`, but if you are using Eclipse it will show you a lint warning and ask you to provide a locale to allow local date formatting. So explicitly setting the default locale is the same as omitting it. – jenzz Jan 16 '13 at 15:30
  • yes I saw this hint, now I know how to use default locale, thank you – Foenix Jan 16 '13 at 17:03
4

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

K_Anas
  • 31,226
  • 9
  • 68
  • 81