2

The below code is returning one day less than what i passed, why is it returning one day less "Fri Aug 27 13:00:00 PDT 2010".

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

   Locale locale = new Locale("en", "US");
   SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", locale);
   TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT-4");

   dateFormat.setTimeZone(timeZone);

   System.out.println(dateFormat.parse("2010-08-28"));
user3157090
  • 517
  • 3
  • 12
  • 29

3 Answers3

4

The reason for the strange output is your system time zone.

For example, on my system I'm working with UTC+2 and your code prints

Fri Aug 27 23:00:00 BST 2010

If I change the system time zone to UTC I get

Fri Aug 27 21:00:00 BST 2010

which makes two hour difference in the output.

So, what appears to be happening is that the date 00:00, 28 Aug 2010 in UTC-4 is calculated to the time zone that's specified in your system settings and then printed in the terminal.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • thank you for answer, but what is the use setting timezone when parsing TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT-4"); dateFormat.setTimeZone(timeZone); – user3157090 Mar 12 '14 at 09:55
  • And it prints 21:00 instead of 20:00 because of the summertime on 27 Aug 2010 – kai Mar 12 '14 at 10:04
1

The output will depend on your system's timezone. What you're parsing is essentially 2010-08-28 00:00:00 on timezone GMT-4. And when you print it it shows this time on your system's timezone.

saladinxu
  • 372
  • 1
  • 2
  • 12
0

See the time at Fri Aug 27 13:00:00 PDT 2010? It's 13:00 PDT, so I'd suggest that you print using a dedicated SimpleDateFormat with the target time zone...

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40