Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting dates to GMT

 
Mike London
Ranch Hand
Posts: 1208
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have some code that takes a date, converts it to a String, then parses it back as a GMT date.

This back and forth conversion make me think there should be an easier way to do this. The toGMTString on the date object is depricated.

Thanks for any ideas how I can shorten this code.

Mike

----------------------------------

Date initial = getTimeStamp():
DateFormat dateFormatter = DateFormat.getInstance();
dateFormatter.setTimeZone (TimeZone.getTimeZone("GMT"));
String gmtS = dateFormatter.format(initial);

Date gmt = null ;
try
{
gmt= formatter.parse(gmtS);
System.out.println(gmt); // prints correct GMT date.
}
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Err, are you aware that your code really isn't doing anything other than truncating the seconds and milliseconds from a timestamp?

Also, it is unclear to me what you are trying to do. What is your spec? You are given a java.util.Date as input. What is your output? Another Date? A String?

One thing to keep in mind is that java.util.Date objects are essentially timestamps -- just a long value. They have no notion of timezone associated with their state. Or you can thing of them as all being in UTC. In either case, "converting the time zone" of a Date object doesn't make sense. But then, I'm not clear on what you are trying to do.
[ May 17, 2006: Message edited by: Jeff Albertson ]
 
Mike London
Ranch Hand
Posts: 1208
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code as I posted it takes a current Timestamp and stores it in GMT format.

I've tested it and it works fine.

I was just wondering if it could be shortened.

Thanks.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm still confused. The input to your "function" is a date given by getTimestamp. What is the output? String gmtS or the output of System.out.println(gmt)? What is the purpose of the second date object?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic