Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Date/Time from Database to milliseconds, hour disappearing

I am having an issue with Dates and timezones.

I have a MySQL InnoDB database which holds two fields DATE(yyyy-MM-dd) and TIME(HH:mm:ss). These are known as to be UTC (0 GMT). My computer is based in CET (+1 GMT).

dateObject is the result from this resultSet.getTime("date_field") (java.sql.Date)

timeObject is a result from this resultSet.getDate("time_field") (java.sql.Time)

In the database DATE is stored as 2014-02-22 and TIME 15:00

System.out.println("Untouched "+dateObject+" "+timeObject);

long date = dateObject.getTime();
long time = timeObject.getTime();

System.out.println("Touched "+new Date(date+time));

Results in the following output:

Untouched 2014-02-22 15:00:00
Touched Sat Feb 22 14:00:00 CET 2014

Why is one hour being skipped off the Touched output? I was expecting the following:

Untouched 2014-02-22 15:00:00
Touched Sat Feb 22 15:00:00 CET 2014

To rumble things up I have tried with the following also:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date(date+time)));

And result:

2014-02-22 14:00:00

All in all. I am expecting GMT+1 to show 16:00(local) and GMT+0 to display 15:00

like image 549
basickarl Avatar asked Jun 22 '26 21:06

basickarl


1 Answers

I think I did answer ma question (Remember timeObject in the db is 15:00:00 at UTC):

TimeZone tz = TimeZone.getTimeZone("Gmt0");
SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfFull.setTimeZone(tz);

Date updateDate = sdfFull.parse(dateObject.toString()+" "+timeObject.toString());

System.out.println(updateDate);

Results in what I was hoping for:

Sat Feb 22 16:00:00 CET 2014
like image 130
basickarl Avatar answered Jun 24 '26 10:06

basickarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!