Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get correct long value from parsed Date (Timezone issue)

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?

like image 327
drayn Avatar asked Feb 15 '13 12:02

drayn


3 Answers

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.

like image 163
n0rm1e Avatar answered Nov 14 '22 20:11

n0rm1e


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.

like image 30
Mark Rotteveel Avatar answered Nov 14 '22 20:11

Mark Rotteveel


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());
like image 45
Klas Lindbäck Avatar answered Nov 14 '22 22:11

Klas Lindbäck