Get the correct long value from parsed date (timezone problem)

I am trying to parse a date from a string and get a long value. A long value will be sent later to the SQL query.

here is 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 result:

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

which is correct, but not what I want, since a long value is obtained on Wed, February 27, 2013 22:00:00 GMT ( http://www.epochconverter.com/ ) (I am in the GMT time zone + 2). And I need to send the correct value for sql.

Is there any way around this without using external libraries?

+5
source share
5 answers

SimpleDateFormat , , , . Midnight 28 GMT + 2 10 27 GMT, 1362002400000. , ( Calendar):

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

, , SimpleDateFormat EET .

- , .

+5

, java GMT :

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());
+1

You convert text and internal ( Date) representations of dates and times without explicitly specifying a time zone. It will never be good .

+1
source
Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    Date date = calendar.getTime();

Use your time zone String:

Timezones

0
source

All Articles