TimeZone issue in Java XMLGregorianCalendar - java

I hope this is not a repeat.
I checked other searches here and all of them seem to talk about "displaying" the date in the right TimeZone format using SimpleDateFormat.
However, my problem is I obtain an XMLGregorianCalendar Object which is let us say in "CET".
I have to find out the format from this object and send the current time also in the same TimeZone as the server.
For eg: I need an XMLGregorianCalendar Object that returns me in this format(with Timezone):
2012-09-19T15:23:36.421+02:00
So I just tried this following snippet which seems to only return the time in local Timezone :(
TimeZone utc = TimeZone.getTimeZone("CET");
GregorianCalendar gc = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
df.setTimeZone(utc);
System.out.println(" - Gregorian UTC [" + df.format(gc.getTime()) + "]")
XMLGregorianCalendar currServTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
System.out.println("currServTime is "+currServTime);

You should include the time zone you're interested in in the GregorianCalendar, either by passing it to the constructor or by setting it afterwards. So either of these lines should work for you:
GregorianCalendar gc = new GregorianCalendar(utc);
gc.setTimeZone(utc);

Related

local to UTC conversion in java

I need to convert local time at a specific city to UTC.
For example ,
convert time in NYC to UTC .
If I pass the local time and country , the service should be able to return the UTC
Is there any library/utility which maps the city/country to timezone and then converts it to UTC ?
I am trying to avoid building a time zone master and do the conversion .
Since this is common problem, if there are any libraries which are already doing it - please revert back
Just need to use Calendar and TimeZone classes?
Define a TimeZone for UTC:
TimeZone tz = TimeZone.getTimeZone("UTC");
And then create the calendar
Calendar cal = Calendar.getInstance(tz);
To retrieve the Date object use calendar.getTime
cal.getTime()
If you already have your date in a Date object (localDate) you can use a formatter:
SimpleDateFormat formatter = new SimpleDateFormat(); formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateinUTC = formatter.format(localDate)

SimpleDateFormat ignores TimeZone

I have read a bunch of posts on this, but, I am obviously missing something. I have date string, and a time zone. I am trying to instantiate a date object as follows:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
java.util.Date dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj);
What is printed is:
Sun Oct 06 09:30:00 EDT 2013
What I want is a date object in UTC format. Not one converted to EDT. What am I doing wrong?
Thanks.
This is because a Date object does not store any timezone information. Date basically only stores the number of milliseconds since the epoch (Jan. 1, 1970). By default Date will use the timezone associated with the JVM. In order to preserve timezone information you should continue using the DateFormat object that you've already got.
See DateFormat#format(Date): http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)
The following should give you what you're looking for:
System.out.println(sdf.format(dateObj));
Try below code, you'll see that the date parsed 1st time is different from the one parsed after setting timezone. Actually the date is parsed as expected in right timezone. It s while printing it gives you get the machines's default TZ.
You could have printed the dateObj.toGMTString() to check the same, but that is deprecated.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj.toString());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj.toString());

Date.toString not showing local timezone

I have a webapp . I am trying to log the time at which certain process got completed.
m_jobResults.addMessage("sum done", new Date().toString());
I am seeing that Date.toString() returns time in GMT as opposed to local timezone . If I write a test java program on same machine , it displays time in my local timezone. Could anyone suggest what is going wrong here.
Also note java.util.Calendar.getInstance().getTimeZone() shows gmt while debugging in webapp where as a sample test code shows as correct local timezone .
First you have to know is:
Date is always UTC-based.
Date does not have a "local instance."
If you want to have a to have a local time zone, use Date with Calendar and/or TimeZone.getDefault().
Use TimeZone.getTimeZone("Europe/Madrid") to get the Barcelona time zone.
If you want to find your server timezone check here:
final TimeZone timeZone = TimeZone.getDefault();
But maybe your server is not located where your user is... so to get user's locale with your server's timezone:
private String getServerTimeZoneDisplayName()
{
final TimeZone timeZone = TimeZone.getDefault();
final boolean daylight = timeZone.inDaylightTime(new Date());
final Locale locale = servletRequest.getLocale();
return timeZone.getDisplayName(daylight, TimeZone.LONG, locale);
}
If you convert a Date to a String directly, as you are doing by calling toString() on it, it will be formatted with the default timezone of the system that the code is running on. This happens to be GMT in your case.
If you want it to be formatted using a different timezone, then use a SimpleDateFormat object and specify the timezone you want on that object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
String text = df.format(new Date());
System.out.println("The date and time: " + text);

how to add days to java simple date format

How should I add 120 days to my current date which I got using simple date format?
I have seen few posts about it but couldn't get it to work,
My code is below:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
//get current date time with Date()
Date date = new Date();
Do I need to use the Calendar library or can I just do it with simple date format?
Basically, you can simple use a Calendar which has the capacity to automatically roll the various fields of a date based on the changes to a single field, for example...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 120);
date = cal.getTime();
Take a closer look at Calendar for more details.
Yes, there is a way to do this using Joda Time, but I could type this example quicker ;)
Update with JodaTime example
The following is an example using JodaTime. You could parse the String value directly using JodaTime, but since you've already done that, I've not bothered...
Date date = ...;
DateTime dt = new DateTime(date);
dt = dt.plusDays(120);
date = dt.toDate();
I would suggest you use Joda DateTime if possible. The advantage is it handles TimeZone very gracefully. Here's how to add days:
DateTime added = dt.plusDays(120);
Reference:
http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#plusDays(int)

Joda time's DateTime converted to java.util.Date strange issue

I ran into a strange issue. Here is a snippet of code that describes it:
DateTimeZone dtz = DateTimeZone.forOffsetHours(0);
DateTime dt = new DateTime(dtz);
System.out.println(dt);
System.out.println(dt.toDate());
the output is:
2012-02-29T17:24:39.055Z
Wed Feb 29 19:24:39 EET 2012
I'm located UTC+2, but this action is supposed to create a java.util.Date object which is initialized for UTC time. What am I missing?
Date doesn't know about a time zone at all - it only represents an instant in time (like Joda Time's Instant type). It's just a number of milliseconds since the Unix epoch. When you call Date.toString(), it always uses the system local time zone for converting that into a readable text form.
So there's nothing wrong here - just an expectations failure over either the meaning of java.util.Date or its toString() behaviour, or both.
(As an aside, prefer DateTimeZone.UTC over creating your own.)
To get a JDK Date that matches Joda's DateTimeconvert to LocalDateTimefirst.
As explained in the other answers, the time in milliseconds does not change depending on the timezone:
DateTime local = DateTime.now()
Date localJDK = local.toDate()
assert localJDK.getTime() == local.toInstant().getMillis()
DateTime differentTimeZone = DateTime.now(DateTimeZone.forID('America/Chicago'))
Date localJDK2 = differentTimeZone.toDate()
assert differentTimeZone.toInstant().getMillis() == localJDK2.getTime()
assert localJDK.getTime() == localJDK2.getTime()
Converting a LocalDateTime to Date will change that:
Date differentTimeZoneJDK = differentTimeZone.toLocalDateTime().toDate()
assert localJDK.getTime() != differentTimeZoneJDK.getTime()
The behaviour you want is this:
Date jdkDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dt.toString("yyyy-MM-dd HH:mm:ss"));
Like Jon noted, JDK date is time zone agnostic. Hope this helps someone.

Categories