Formatting date in Java

I am having a problem with formating a date using Java. The date formatter seems to parse my string using BST (British Summer Time) and not GMT+0 as defined by +0000 in the dateStr string in the code below.

String dateStr = "Tue Oct 02 01:06:00 +0000 2012";
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");  
Date date = df.parse(dateStr);

// Test the date        
System.out.println(date.toString());

When I run the above code I get:

Tue Oct 02 02:06:00 BST 2012

Which is evidently not what I want. A useful point of information might be that when I run the following:

System.out.println(TimeZone.getDefault().getDisplayName());

I get:

Greenwich Mean Time

The output I'm trying to get is

Tue Oct 02 01:06:00 GMT 2012

I've already tried .setTimeZone on df but to no avail.

Upvotes: 1

Views: 157

Answers (4)

Matthew Ammeter
Matthew Ammeter

Reputation: 84

Note that Tue Oct 02 02:06:00 BST 2012 is the same time as Tue Oct 02 01:06:00 +0000 2012, just expressed in a different time zone. java.util.Date doesn't really deal with time zones, so as far as its concerned, there is no difference. The Date object you've constructed represents the correct date and time you want.

The Date.toString() method is essentially just a formatter that uses your JRE default TimeZone in its formatting. If you want to test that the Date object is correct, then you should build a java.util.Date object (using java.util.Calendar - most of the Date constructors have been deprecated) to test against. If you want to create a display string, then you should use the SimpleDateFormatter instance you've already created to format the Date object.

If you do need an object that stores TimeZone information, then you should use java.util.Calendar. java.util.Date is almost deprecated to the point of being unusable anyway. Or, do the same as I am and wait for the new Data and Time API coming out in Java 8.

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

The .toString() method is using your locale when printing the date.

Use:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(date));

Upvotes: 1

zidom
zidom

Reputation: 21

you can try like here:

DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy",
                Locale.CANADA);

add Local args to SimpleDateFormat constructor

Upvotes: 0

Cheung Brian
Cheung Brian

Reputation: 755

I understand that BST is already deprecated in SE 7.

Upvotes: 0

Related Questions