1

I have seconds like below:

1320130800

I need to convert the value into Date and Time Combination format. While formatting I got the result as follows:

Tuesday,November 1,2011 2:00,AM

But the correct result is as follows:

Tuesday,November 1,2011 7:00,AM

For the above format conversion I used the below code:

 long millis = 1320130800*1000;
           Date date = new Date(millis);
           SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm a");
           String formattedDate = sdf.format(date);
           System.out.println(formattedDate);

Can any one guide me to get the correct answer?

T.Rob
  • 31,522
  • 9
  • 59
  • 103
Pradeep
  • 129
  • 3
  • 10

2 Answers2

5

Sounds like it's just a time zone issue - you need to set the time zone for the formatter:

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

(Note that in your sample code, long millis = 1320130800*1000; doesn't work as it performs the multiplication in 32-bit arithmetic; you need something like long millis = 1320130800L*1000;.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Use the Calendar API instead.

After you have the Date object, construct a Calendar object (getInstance() returns one with the default Time Zone) and do setDate(Date) on it and parse it like that.

Alternatively, you can take a look at Joda Time APIs since they are easy to use.

Regards!

Mechkov
  • 4,294
  • 1
  • 17
  • 25
  • He's formatting, not parsing - and `DateFormat` always takes a Date, not a `Calendar`. Joda Time is an admirable suggestion if there's anything more going on date/time-wise though. – Jon Skeet Nov 25 '11 at 19:27
  • Fair enough! I assumed he is just showing the formatted Date, just so we can observe that it is not storing the correct date or hour to be more precise. Regards! – Mechkov Nov 25 '11 at 19:34