Link to home
Start Free TrialLog in
Avatar of vaibhavbajpai
vaibhavbajpai

asked on

Converting local date to GMT

How do I need to convert the java.util.date iam setting in my java code to GMT and retrieve the same date back , reconverting  it back to the desired TimeZOne.

Please send me the necessary code
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Back from where? You don't need to alter the Date as Date contains no time zone information. You just need to format it in the desired time zone
Avatar of vaibhavbajpai
vaibhavbajpai

ASKER

When we store datetime in the database we have to be aware of which timezone it is going to be.
Our prod databases can be in a different location from our production servers running the application.Is there a way of knowing the timezone from the database.

Changing the default timezone in database is not easy.How can I convert the locale date into GMT and store it in database and while retrieving back is it guranteed that it would be int GMT ? and then format the date accordingly before we send it back to the front end.

Iam using MySQL
You need to store the time zone and format the date using that user's timezone
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TestDate {

      public TestDate() {
            super();
            // TODO Auto-generated constructor stub
      }

      /**
       * @param args
       */
      public static void main(String[] args) {
            Date date = new Date();
            System.out.println("Current Date :"+date.toString());
            TimeZone gmt = TimeZone.getTimeZone("GMT");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(gmt);
            String dateString = sdf.format(date);
            System.out.println("Date String :"+dateString);
            try {
                  Date newDate = sdf.parse(dateString);
                  System.out.println("Date after formatting : "+sdf.format(newDate));
                  System.out.println("Converting using toString : "+newDate.toString());
            } catch (ParseException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }
}

Output :

Current Date :Fri May 12 02:49:57 GMT+05:30 2006
Date String :2006-05-11 21:19:57
Date after formatting : 2006-05-11 21:19:57
Converting using toString : Fri May 12 02:49:57 GMT+05:30 2006

Why is value for "Converting using toString" not the GMT value, Iam in India and the GMT difference is +5hr30min
>>Why is value for "Converting using toString" not the GMT value

Because you're not printing it using the DateFormat you've set. You're printing it using the system DateFormat
When iam outputting in the method
       /**
       * Converts the Date in the DB to GMT date
       *
       * @param cookieExpiryDate
       * @return gmtDate
       * @throws ParseException
       */
      public Date toGMT(Date cookieExpiryDate) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat(Messages.getString("dateFormat"));
            sdf.setTimeZone(TimeZone.getTimeZone(Messages.getString("timeZone")));
            String dateString = sdf.format(cookieExpiryDate);
            Date gmtDate = sdf.parse(dateString);
            System.out.println("GMT Date : "+sdf.format(gmtDate));
            return gmtDate;
      }
Date format iam using is "yyyy-MM-dd HH:mm:ss"
Output : GMT Date : 2006-05-11 22:04:57 , this right considering iam in India and GMT diff is +5:30

But when I call this method somewhere else like

        /**
       * @param cookieExpiry
       */
      private void printObject(CookieExpiry cookieExpiry) {
            SimpleDateFormat sdf = new SimpleDateFormat(Messages.getString("dateFormat"));
            Date newDate = null;
            try {
                  newDate = cookieMgr.toGMT(cookieExpiry.getCookieExpiryDate());
            } catch (ParseException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
            }
            if (cookieExpiry != null) {
                  System.out.println("UUID               : "
                              + cookieExpiry.getUuidMailDetail().getUuid());
                  System.out.println("MAIL ADDRESS       : "
                              + cookieExpiry.getUuidMailDetail().getMailAddress());
                  System.out.println("COOKIE VALUE       : "
                              + cookieExpiry.getCookieValue());
                    System.out.println("COOKIE EXPIRY DATE : " + sdf.format(newDate));
            } else {
                  System.out.println("Record doesn't contain any details");
            }
      }
i get output as

UUID               : wamdev01
MAIL ADDRESS       : wamdev01@earthlink.net
COOKIE VALUE       : 47250620-3555-11d7-86f0-080020b6c5d9
COOKIE EXPIRY DATE : 2006-05-12 03:34:57

Why is COOKIE EXPIRY DATE not equal to GMT Date
you need to store the date in your database as GMT, plus also store the toimezone offset if you want to know what timezone it was entered in.
>>Output : GMT Date : 2006-05-11 22:04:57 , this right considering iam in India and GMT diff is +5:30

>>COOKIE EXPIRY DATE : 2006-05-12 03:34:57

Looks like you've added another 5.5 hours

Do I need to create a separate column for that and how would I be storing it?

If I store the GMT date then to retrieve it back do need to apply the same date format?
You could use a long column as data offsets are in milliseconds. As i mentioned earlier, Date itself has no zone info
Actually an int will do
Okay....so when retrieving the date back what how do I get the original date back from the GMT that is stored and how would I be using the offset to achieve this ?
> Do I need to create a separate column for that and how would I be storing it?

if you need to actually know the timezone you do, the important part is to setup your database to store GMT.
Iam using MySQL....what do I need to setup for storing GMT
So if I need to store GMT in the database....do I follow the same process of getting the GMT date using SimpleDateFormat and persisting it in the Database

ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>what do I need to setup for storing GMT

Your database shouldn't change any Date that is entered so why would you think there is any problem? A Date is essentially a number *with no timezone information*
I am trying this

Calendar cal = new GregorianCalendar();
                  cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                  cal.getTime();
                  System.out.println("GMT Time :"+cal.getTime().toString());

Output :
GMT Time :Fri May 12 15:47:57 GMT+05:30 2006

but this is not the GMT time....

How do I convert my local time to GMT for saving in the database ?
> but this is not the GMT time....
> How do I convert my local time to GMT for saving in the database ?

Thats just the toString() method formatting it using the current timezone.

Just store the date directly to the database with the appropriate database settings.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What would be the appropriate Database settings i need to do ?
see me earluer post
Oh yeah....should I use java.sql.Date or java.util.Date
If you want time info, java.sql.Timestamp, else java.sql.Date
I am trying to set the GMT date as
cookieDetail.setCookieExpiryDate(cookieMgr.toGMT(new Date()));
following are the functions iam using for converting to GMT
      public Date toGMT(Date date){
            SimpleDateFormat sdf = getDateFormat(TimeZone.getTimeZone(Messages.getString("timeZoneGMT")));
            try {
                  return sdf.parse(sdf.format(date));
            } catch (ParseException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
            return date;
      }

      public SimpleDateFormat getDateFormat(TimeZone timeZone) {
            SimpleDateFormat sdf = new SimpleDateFormat(Messages.getString("format"));
            sdf.setTimeZone(timeZone);
            return sdf;
      }

But the DB shows me the date as per my timezone. iam using Hibernate to perform DB operations

Is this the right of storing GMT dates ?
>>are the functions iam using for converting to GMT

I don't know how many times i have to say this: Date has no timezone info and doesn't need converting

A Date is an example of a model and its view is the  formatter. You need to change the view, not the model
for the cookie just store the value date.getTime() as the local timezone is already known.

> But the DB shows me the date as per my timezone. iam using Hibernate to perform DB operations

r u storing it as gmt as i explained earlier.

But before converting I need to know what timezone the database is storing in before I can convert.
The database can be in CST or EST while our application server can be in PST and the user can be in GMT.
I was more looking for a  method to know the database timezone dynamically and then I can use the methods for converting to the timezone.

Once our application is deployed in production the SA's can change the dbase boxes and put them in god knows what timezone.So when I store the data in the database since the mysql doesn't store the timezone I was wondering we can either store the timezone of our date in a separate column or find out the timezone of the database server before we convert.

Let me know if there is a way to find out what timezone the mysql stores in.By default it stores in the timezone of the system ie box where it is on.Also if we can change it to store it in GMT that will also be good.
>>But before converting I need to know what timezone the database is storing in before I can convert.

The database will store the date you give it. If you pass it the time now (1147453587612 as i write) then it will store 1147453587612

I've already described how you store the timezone - use an int column
> But before converting I need to know what timezone the database is storing in before I can convert.

Are you sure you need to convert at all?

> The database can be in CST or EST while our application server can be in PST and the user can be in GMT.

Thats why I suggested handling everything as GMT

> So when I store the data in the database since the mysql doesn't store the timezone I was wondering we can either store the timezone of our date in a separate column or find out the timezone of the database server before we convert.

If you do need to know the timezone then store the offset in a seperate column as I originally suggested

> Let me know if there is a way to find out what timezone the mysql stores in.

You don't need to know, as you can override it.

> Also if we can change it to store it in GMT that will also be good.

I already showed you how
How can convert a long form value as in "1147676097000" to a Date object

when I give like "new Date(1147676097000)" it says "literal 1147676097000 of type int is out of range"
new Date(1147676097000L)
I tried doing this....why do I get the same Date value for diffrent long values

System.out.println("COOKIE EXPIRY DATE - Converting from long value : "+ new Date(1147676097091L));
System.out.println("COOKIE EXPIRY DATE - Converting from long value : "+ new Date(1147676097000L));

COOKIE EXPIRY DATE - Converting from long value : Mon May 15 12:24:57 GMT+05:30 2006
COOKIE EXPIRY DATE - Converting from long value : Mon May 15 12:24:57 GMT+05:30 2006
because the long value is in milliseconds
As posted i am persisting the date as a long value but when retrieving it back to convert to the Date object using as new Date(1147676097091L) iam not able to get the GMT date...

Is there anyother way to do this without using the SimpleDateFormat ?
>>Is there anyother way to do this without using the SimpleDateFormat ?

What's the problem about using a DateFormat?
I want to use the GMT date for further computation and since the long date I got after format didn't have a significant difference from the original date....i was wondering whether futher computation would work or not

       /**
       * Returns the parsed date with the desired TimeZone
       *
       * @param date
       * @param timeZone
       * @return date : Date
       */
      public Date getTimeZoneDate(Date date,TimeZone timeZone){
            Date timeZoneDate = new Date();
            System.out.println("current long date:"+date.getTime());
            SimpleDateFormat sdf = getDateFormat(timeZone);
            try {
                  timeZoneDate = sdf.parse(sdf.format(date));
            } catch (ParseException e) {
                  //TODO:throw your custom application exception
            }
            System.out.println("Long Date :"+timeZoneDate.getTime());
            return timeZoneDate;
      }

       /**
       * Returns the SimpleDateFormat set with desired TimeZone
       *
       * @param timeZone
       * @return sdf : SimpleDateFormat
       */
      private SimpleDateFormat getDateFormat(TimeZone timeZone) {
            SimpleDateFormat sdf = new SimpleDateFormat(Messages.getString("format"));
            sdf.setTimeZone(timeZone);
            return sdf;
      }
System.out.println("current long date:"+date.getTime()); and
System.out.println("Long Date :"+timeZoneDate.getTime()); show a very insignificant difference in milliseconds

Why is that so..?
>>I want to use the GMT date for further computation

There's no such thing as 'the GMT date'. That's just one way of many of formatting the long value

>>Why is that so..?

Because both dates are created with milliseconds of each other and both use the default DateFormat to print
> Is there anyother way to do this without using the SimpleDateFormat ?

Yes, just store the date directly.