I have a timestamp in string, which is in UTC timezone, i want to read it as is in UTC timezone using DateTime in joda time library.
Example:
String utcTs = "2016-06-01T14:46:22.001Z";
when i try below stmt., DateTime is reading it and converting to servertimezone where ever the application is running!!
DateTime dtUtcTs = new DateTime(utcTs);
Is there a way i can force the DateTime to read the string timestamp as UTC ?
My application server is in CST, and when print the date with SOP stmt like below, i am observing CST time instead of UTC!!
System.out.println(dtUtcTs)
==> gives me date in server where the application is running!!
Thanks a lot!!
import org.joda.time.DateTime;
public class TestClass {
public static void main(String[] args) {
String utcTs = "2016-06-01T14:46:22.001Z";
DateTime dtUtcTs = new DateTime(utcTs);
System.out.println(dtUtcTs)
}
}
below is the output i see, my application server is in CST zone
2016-06-01T09:46:22.001-05:00
using joda time version 2.9.1
You can just use the overload of the DateTime
constructor that takes a DateTimeZone
:
DateTime dtUtcTs = new DateTime(utcTs, DateTimeZone.UTC);
Another option is to use a DateTimeFormatter
so you can specify exactly the format you expect, and what time zone you want.
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2016-06-01T14:46:22.001Z";
DateTime dt = ISODateTimeFormat.dateTime()
.withZone(DateTimeZone.UTC)
.parseDateTime(text);
System.out.println(dt);
}
}
See more on this question at Stackoverflow