Question

I know this is probably a stupid question, but I am having the hardest time converting a Date to a string using SimpleDateFormat. I have a local date

"Thu Jul 18 18:56:51 PDT 2013"

And I am trying to convert it directly in the format

"yyyy-MM-dd'T'hh:mm:ss".

What I want the string to look like is this :

"2013-07-18T18:56:51"

what I am getting is this:

"2013-07-18T06:56:51"

Any help would be appreciated.

Was it helpful?

Solution

You're using hh, which is the 12-hour clock. You want to use HH instead:

"yyyy-MM-dd'T'HH:mm:ss"

From the docs for SimpleDateFormat

  • hh - Hour in am/pm (1-12)
  • HH - Hour in day (0-23)
  • kk - Hour in day (1-24)
  • KK - Hour in am/pm (0-11)

(Quite why they reversed the capitalization in terms of 12/24 hours for kk/KK is beyond me, but then the whole of the Java date/time API is crazy...)

Also, while it looks like you're currently okay, it's worth thinking about the time zone aspect. A Date doesn't have any concept of a time zone or calendar - it's just an instant in time. The SimpleDateFormat does have an associated time zone and calendar (and culture) so make sure they're correct for your purposes.

OTHER TIPS

h Hour in am/pm (1-12)

H Hour in day (0-23)

k Hour in day (1-24)

K Hour in am/pm (0-11)

use HH

Class SimpleDateFormat doc

You must use HH rather than hh:

yyyy-MM-dd'T'HH:mm:ss

Letter Date or Time Component Presentation Examples

H Hour in day (0-23) Number 0

k Hour in day (1-24) Number 24

K Hour in am/pm (0-11) Number 0

h Hour in am/pm (1-12) Number 12

You can read more about Date here.

package com.stackoverflow.experiments;

import java.text.SimpleDateFormat; import java.util.Calendar;

public class SimpleDateFormatExperiment {

/**
 * 
 */
public SimpleDateFormatExperiment() {
    // TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(Calendar.getInstance().getTime()));
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top