It's not a secret anymore!*
The moose likes Java in General and the fly likes Java Date problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Date problem" Watch "Java Date problem" New topic

Java Date problem

Hs Raveendran

Joined: Feb 05, 2010
Posts: 23

In java web application while storing the date into a database and rendering from the database do we need to convert the date in to UTC format

in DB i have the datefield datatype as datetime

The problem i am getting is the date stored in to the DB properly but while rendering its giving one day lesser than the current date if the server or db time zone is different.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074

There are a few things you have to understand about java.util.Date and java.sql.Date objects.

These objects represent an "absolute" moment in time, and they do not contain any timezone information by themselves.

When you want to display a date in a specific timezone, you can convert the Date object to a string for display by using a DateFormat object. You set the timezone on the DateFormat object, to let it know in what timezone you want to have the date displayed. For example:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 7553

Hs Raveendran wrote:In java web application while storing the date into a database and rendering from the database do we need to convert the date in to UTC format....

No you don't (or you almost certainly don't). As Jesper said, Java dates (and most database dates too) are an offset from a fixed point in time; and that time is already UTC (or as close as makes no difference).

It's much more likely that your rendering issues have to do with choosing the wrong timezone for display. For example, the database more than likely displays time according to its local timezone by default (and Java definitely does). If you want to see the time in UTC form, then you should follow his advice.


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
I agree. Here's the link:
subject: Java Date problem
Similar Threads
f:convertDateTime and data type conversion
Getting error while inserting data into table
Java Performance
Problem with Date and Time
Writing databse scripts which inturn checks for the tables, columns and constraints