5

I'm trying to parse a date from a String and get the long value. The long value will be later sent to an SQL query.

here's my code:

String dayDate = "28-02-2013";            
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date day = new Date();
try {
    day = sdf.parse(dayDate);
} catch (ParseException pe) {
    pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ "  long : " + day.getTime());

which gives the following output:

day : Thu Feb 28 00:00:00 EET 2013  long : 1362002400000

which is correct but not what I want since the long value results in Wed, 27 Feb 2013 22:00:00 GMT (http://www.epochconverter.com/) (I'm in a GMT+2 timezone). And i need to send to correct long value to sql.

Is there anyway to work around this without using external libraries?

MT0
  • 143,790
  • 11
  • 59
  • 117
drayn
  • 303
  • 3
  • 9

5 Answers5

5

SimpleDateFormat is locale-aware, meaning the date it parses is in your timezone. Midnight 28 Feb in GMT+2 is actually 10pm 27 Feb in GMT, the long value 1362002400000. I would add this to get the parsing right (would't bother using Calendar):

sdf.setTimeZone(TimeZone.getTimeZone("GMT"))

Again, when you print this date it uses SimpleDateFormat and that's why you can see EET in the output.

Passing this to database is a different story though once you get this right.

n0rm1e
  • 3,796
  • 2
  • 28
  • 37
1

Use DateFormat.setCalendar(Calendar cal) to set a Calendar with GMT as its timezone, or use DateFormat.setTimeZone(TimeZone zone) with the GMT TimeZone. That will ensure that the resulting Date will be 00:00:00 in GMT instead of in EET.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
1

If you add a timezone specifier to your string you can force java to use GMT for the conversion:

String dayDate = "28-02-2013";            
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy z"); // z is a timezone specifier
Date day = new Date();
try {
    day = sdf.parse(dayDate + " GMT"); // Use GMT timezone.
} catch (ParseException pe) {
    pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ "  long : " + day.getTime());
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
1

You are converting between text and internal (Date) representations of dates and times without explicitly stating the time-zone. That never goes well.

Community
  • 1
  • 1
Raedwald
  • 46,613
  • 43
  • 151
  • 237
0
Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    Date date = calendar.getTime();

Use your timezone String:

TimeZones

Edgard Leal
  • 2,592
  • 26
  • 30