Converting datetime to string, wrong hours

32,522

Solution 1

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?

Solution 2

This will do it for you:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd  HH:mm", Locale.getDefault());
String sdt_ = sdf.format(dt_);

Solution 3

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

Share:
32,522
Foenix
Author by

Foenix

I am compleatly new in android and java. Thank you all very much for you help!

Updated on January 17, 2020

Comments

  • Foenix
    Foenix over 4 years

    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
    
  • Foenix
    Foenix over 11 years
    I do not see any 'kk' by your link . I used HH in my pattern.
  • Foenix
    Foenix over 11 years
    thank you, it is working (with or without Locale.getDefault())
  • Berťák
    Berťák over 11 years
    see my other answer, if you still want to use android.text.format.DateFormat :-)
  • K_Anas
    K_Anas over 11 years
    @Foenix see in the table k hour in day (1-24) (Number) 24
  • jenzz
    jenzz over 11 years
    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.
  • Foenix
    Foenix over 11 years
    yes I saw this hint, now I know how to use default locale, thank you