user2299225
user2299225

Reputation: 11

To get the date time in the format I give

I have a Java Date object containing date and time information, e.g.2010-11-11T09:30:47. I want to write a method that will convert this Date object to the following format. "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

I wrote the following code.

    private Calender getValue(Date dateObject) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

    String timestamp = formatter.format(dateObject);

    System.out.println("Created GMT cal with date [" + timestamp + "]");

    }

When I run the program, it is printing

Created GMT cal with date [2010-11-11T04:00:47.000Z]

What I gave is "2010-11-11T09:30:47", My time is 09:30:47. What it is printing is "04:00:47".

Why the time is changing 9.30 to 4.00.?

What do I need to do to get the same time as I give. Like 2010-11-11T09:30:47.000Z

Thanks a lot.

Upvotes: 0

Views: 230

Answers (3)

Rahul Bobhate
Rahul Bobhate

Reputation: 5082

You just need to remove the following line

formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

Because you are setting the Timezone to be GMT, whereas your timezone is GMT + 5.30. That is the reason when you set the time to 9.30, you will get 9.30 - 5.30 = 4.00.

You can just use the following code:

private void getValue(Date dateObject) 
{
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    String timestamp = formatter.format(dateObject);
    System.out.println("Created GMT cal with date [" + timestamp + "]");
}

Upvotes: 1

Jaydeep Rajput
Jaydeep Rajput

Reputation: 3673

Remove formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  String timestamp = formatter.format(new Date());
  System.out.println("Created GMT cal with date [" + timestamp + "]");

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691913

Your date probably has the time 09:30:47 in your time zone. But you configured the date format to the GMT time zone. So it's displaying the time as it is in the GMT time zone.

If you used another date format to parse the input string and get a Date object, make sure this oter date format also uses the GMT time zone.

To get more help, show us how you create the Date object passed to your method.

Upvotes: 1

Related Questions