• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2338
  • Last Modified:

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
0
vaibhavbajpai
Asked:
vaibhavbajpai
  • 16
  • 14
  • 10
  • +1
3 Solutions
 
CEHJCommented:
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
0
 
vaibhavbajpaiAuthor Commented:
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
0
 
CEHJCommented:
You need to store the time zone and format the date using that user's timezone
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
vaibhavbajpaiAuthor Commented:
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
0
 
CEHJCommented:
>>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
0
 
vaibhavbajpaiAuthor Commented:
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
0
 
objectsCommented:
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.
0
 
CEHJCommented:
>>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

0
 
vaibhavbajpaiAuthor Commented:
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?
0
 
CEHJCommented:
You could use a long column as data offsets are in milliseconds. As i mentioned earlier, Date itself has no zone info
0
 
CEHJCommented:
Actually an int will do
0
 
vaibhavbajpaiAuthor Commented:
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 ?
0
 
objectsCommented:
> 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.
0
 
vaibhavbajpaiAuthor Commented:
Iam using MySQL....what do I need to setup for storing GMT
0
 
vaibhavbajpaiAuthor Commented:
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

0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> what do I need to setup for storing GMT

Might be better answered in the MySQL TA. Though it might be better not to do it because it might not be supported in all data-bases, so then your Java code will not work on all DBs. I suggest you store the offset in the DB as you have been told and then use SimpleDateFormat to format it. Also see these:

http://javaalmanac.com/egs/java.util/GetTimeOtherZone.html

http://javaalmanac.com/egs/java.util/GetTimeOtherZone2.html

0
 
objectsCommented:
> Iam using MySQL....what do I need to setup for storing GMT

in your connection string add "useTimezone=true&serverTimezone=GMT"

> do I follow the same process of getting the GMT date using SimpleDateFormat and persisting it in the Database

Not really, you should be able to avoid using SDF at all and use a PreparedStatement to insert the Date directly.
If you can treat everything as GMT you can avoid any unnecessary hassles with timezome and formatting altogether.
0
 
CEHJCommented:
>>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*
0
 
vaibhavbajpaiAuthor Commented:
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 ?
0
 
objectsCommented:
> 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.
0
 
CEHJCommented:
>>How do I convert my local time to GMT for saving in the database ?

I keep saying - you don't need to convert anything
0
 
vaibhavbajpaiAuthor Commented:
What would be the appropriate Database settings i need to do ?
0
 
objectsCommented:
see me earluer post
0
 
vaibhavbajpaiAuthor Commented:
Oh yeah....should I use java.sql.Date or java.util.Date
0
 
CEHJCommented:
If you want time info, java.sql.Timestamp, else java.sql.Date
0
 
vaibhavbajpaiAuthor Commented:
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 ?
0
 
CEHJCommented:
>>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
0
 
objectsCommented:
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.

0
 
vaibhavbajpaiAuthor Commented:
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.
0
 
CEHJCommented:
>>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
0
 
objectsCommented:
> 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
0
 
vaibhavbajpaiAuthor Commented:
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"
0
 
objectsCommented:
new Date(1147676097000L)
0
 
vaibhavbajpaiAuthor Commented:
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
0
 
objectsCommented:
because the long value is in milliseconds
0
 
vaibhavbajpaiAuthor Commented:
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 ?
0
 
CEHJCommented:
>>Is there anyother way to do this without using the SimpleDateFormat ?

What's the problem about using a DateFormat?
0
 
vaibhavbajpaiAuthor Commented:
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..?
0
 
CEHJCommented:
>>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
0
 
objectsCommented:
> Is there anyother way to do this without using the SimpleDateFormat ?

Yes, just store the date directly.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 16
  • 14
  • 10
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now