JodaTime - Display time in its own timezone - java

My app is using JodaTime to manage date parsing and formatting.
I have this timestamp: 2018-07-24T15:30:00-07:00.
How can display it as 3:30pm, regardless of the user's whereabouts?

Following code will print "3:30pm":
DateTimeFormatter iso = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
DateTime tsp = iso.parseDateTime("2018-07-24T15:30:00-07:00");
DateTimeFormatter out = DateTimeFormat.forPattern("h:mma").withLocale(Locale.ENGLISH);
System.out.println(tsp); // 2018-07-24T15:30:00.000-07:00
System.out.println(out.print(tsp).toLowerCase()); // 3:30pm
The main problem is just that the parser does not retain the parsed offset of -7:00 but shifts it to your system timezone unless you also call withOffsetParsed().

Related

Convert UTC date to Local Time in Android? [duplicate]

This question already has answers here:
Android convert UTC Date to local timezone [duplicate]
(2 answers)
Closed 5 years ago.
I have a date String like 2017-09-16T05:06:18.157 and I want to convert it to local time (IST). In Indian Standard Time it will be around 2017-09-16 10:36:18.
With Joda-Time, I have tried to convert it to local but I was not able to do it.
Below is my code:
private String getConvertDate(String date_server) {
DateTimeFormatter inputFormatter = DateTimeFormat
.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
.withLocale(Locale.US);
DateTime parsed = inputFormatter.parseDateTime(date_server);
DateTimeFormatter outputFormatter = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss")
.withLocale(Locale.US)
.withZone(DateTimeZone.getDefault());
return outputFormatter.print(parsed);
}
Good you found a solution with SimpleDateFormat. I'd just like to add more insights about it (basically because the old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs).
The input String (2017-09-16T05:06:18.157) contains only the date (year/month/day) and time (hour/minute/second/millisecond), but no timezone information. So, when calling parseDateTime, Joda-Time just assumes that it's in the JVM default timezone.
If you know that the input is in UTC, but the input itself has no information about it, you must tell it. One way is to set in the formatter:
// set the formatter to UTC
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
.withZone(DateTimeZone.UTC);
// DateTime will be in UTC
DateTime parsed = inputFormatter.parseDateTime("2017-09-16T05:06:18.157");
Another alternative is to first parse the input to a org.joda.time.LocalDateTime (a class that represents a date and time without a timezone), and then convert it to a DateTime in UTC:
// parse to LocalDateTime
DateTime = parsed = LocalDateTime.parse("2017-09-16T05:06:18.157")
// convert to a DateTime in UTC
.toDateTime(DateTimeZone.UTC);
Both produces the same DateTime, corresponding to UTC 2017-09-16T05:06:18.157Z.
To format it to "IST timezone" (which is actually not a timezone - more on that below), you can also set the timezone in the formatter:
// convert to Asia/Kolkata
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
.withZone(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(outputFormatter.print(parsed));
Or you can convert the DateTime to another timezone, using the withZone() method:
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
// convert to Asia/Kolkata
System.out.println(outputFormatter.print(parsed.withZone(DateTimeZone.forID("Asia/Kolkata"))));
Both will print:
2017-09-16 10:36:18
In your code you're using DateTimeZone.getDefault(), that gets the JVM default timezone (with some tricky details). But the default timezone can be changed without notice, even at runtime, so it's always better to specify which one you want to use.
Also, keep in mind that short names like IST are not real timezones. Always prefer to use IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard. Just check in this list that IST can be "India Standard Time", "Israel Standard Time" and "Irish Standard Time".
You can get a list of available timezones (and choose the one that fits best your system) by calling DateTimeZone.getAvailableIDs().
Java new Date/Time API
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
If you can't (or don't want to) migrate from Joda-Time to the new API, you can ignore this section.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
This new API has lots of different date/time types for each situation.
First, you can parse the input to a org.threeten.bp.LocalDateTime, then I use a org.threeten.bp.ZoneOffset to convert it to UTC, resulting in a org.threeten.bp.OffsetDateTime.
Then, I use a org.threeten.bp.ZoneId to convert this to another timezone, and use a org.threeten.bp.format.DateTimeFormatter to format it (this is basically what's suggested by #Ole V.V's comment - just to show how straightforward it is, as there aren't anything much different to do):
// parse to LocalDateTime
OffsetDateTime parsed = LocalDateTime.parse("2017-09-16T05:06:18.157")
// convert to UTC
.atOffset(ZoneOffset.UTC);
// convert to Asia/Kolkata
ZoneId zone = ZoneId.of("Asia/Kolkata");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(outputFormatter.format(parsed.atZoneSameInstant(zone)));
The output is:
2017-09-16 10:36:18
try this code:
String serverdateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public String convertServerDateToUserTimeZone(String serverDate) {
String ourdate;
try {
SimpleDateFormat formatter = new SimpleDateFormat(serverdateFormat, Locale.UK);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(serverDate);
TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
SimpleDateFormat dateFormatter = new SimpleDateFormat(serverdateFormat, Locale.UK); //this format changeable
dateFormatter.setTimeZone(timeZone);
ourdate = dateFormatter.format(value);
//Log.d("OurDate", OurDate);
} catch (Exception e) {
ourdate = "0000-00-00 00:00:00";
}
return ourdate;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
Date myDate =simpleDateFormat.parse(rawQuestion.getString("Asia/Kolkata"));
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(myDate);

Saving time data (with Zone) in Oracle DB not working because of Java SimpleDateFormat issue

I have a field that is defined as TIMESTAMP WITH TIME ZONE.
The value to be saved starts off as: "09-23-2019 10:03:11 pm" in the zone of US/Hawaii.
This is what I am trying to save to the DB (all of the date information plus the Zone)
The database stores time information in UTC format.
As of now, the date is being stored in the DB so that it looks like this:
DAYS
---------------------------------------------------------------------------
23-SEP-19 10.03.11.000000 PM -05:00
23-SEP-19 10.03.11.000000 PM -05:00
During the processing, it runs through this code:
dateStr: the date (as seen above)
ZoneLoc: 'US/Hawaii'
public Calendar convDateStrWithZoneTOCalendar(String dateStr,
String ZoneLoc) throws Exception {
// convert the string sent in from user (which uses AM/PM) to one that uses military time (24HR)
// it
String formattedDate = null;
DateFormat readFormat = new SimpleDateFormat(this.getPattern());
DateFormat writeFormat = new SimpleDateFormat("MM-dd-yyyy'T'HH:mm:ss'Z'");
writeFormat.setTimeZone(TimeZone.getTimeZone(ZoneLoc));
Date date = null;
date = readFormat.parse(dateStr);
formattedDate = writeFormat.format(date);
// see if you can parse the date needed WITH the TimeZone
Date d;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone(ZoneLoc));
d = sdf.parse(formattedDate);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
system.out.println(" ZONELOC VALUE " + ZoneLoc);
system.out.println(" RETURNED VALUE " + cal );
return cal;
}
The calendar info that is returned is:
ZONELOC VALUE IS US/Hawaii
RETURNED VALUE IS
java.util.GregorianCalendar[time=1577678591000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=11,WEEK_OF_YEAR=1,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=363,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=3,SECOND=11,MILLISECOND=0,ZONE_OFFSET=-21600000,DST_OFFSET=0]
It looks as though US/Hawaii is not being set in the RETURNED VALUE.
What can I do to be sure that this gets set?
After that, I can place it in the DB and see if the setting will "stick" and not revert back to America/Chicago
Update
#Patrick H - thanks for the input. I made the change with the pattern you specified and was able to save the data. It now looks like this:
2017-08-02 13:38:49 TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [26] as [TIMESTAMP] - [java.util.GregorianCalendar[time=1569294191000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=8,WEEK_OF_YEAR=39,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=266,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=3,SECOND=11,MILLISECOND=0,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]]
The data in the DB looks like this:
23-SEP-19 10.03.11.000000 PM -05:00
The Zone is still America/Chicago even through US/Hawaii was specified. How can one get US/Hawaii to stick and not revert back to America/Chicago?
According to this output:
java.util.GregorianCalendar[time=1569294191000,...
The time value above (which means 1569294191000 milliseconds since unix epoch (1970-01-01T00:00Z)) is equivalent to 09-23-2019 10:03 PM in Chicago. That's because readFormat is using the system's default timezone (which is probably America/Chicago, just check the value of TimeZone.getDefault()).
To parse the input 09-23-2019 10:03:11 pm and consider it as the local time in Hawaii, you just need to set the corresponding timezone to the SimpleDateFormat instance (in this case, to readFormat, as it needs to know in what timezone the input date is - as you didn't set any, it uses the system's default). You also don't need the other formatters (writeFormat and sdf), only one formatter can be used to get the corresponding date:
SimpleDateFormat parser = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
// the input is in Hawaii timezone
parser.setTimeZone(TimeZone.getTimeZone("US/Hawaii"));
Date date = parser.parse("09-23-2019 10:03:11 pm");
The date above will be equivalent to 10:03 PM in Hawaii. Actually, the date itself contains just the milliseconds from the unix epoch (date.getTime() returns 1569312191000) and has no format nor any timezone information.
You can then set it to a Calendar instance (don't forget to set the calendar's timezone):
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
cal.setTime(date);
It's been some time since I used oracle's timestamp with timezone type, but I think that'll be enough to save the correct values. The value of calendar is:
java.util.GregorianCalendar[time=1569312191000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="US/Hawaii",offset=-36000000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=8,WEEK_OF_YEAR=39,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=266,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=3,SECOND=11,MILLISECOND=0,ZONE_OFFSET=-36000000,DST_OFFSET=0]
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
One of the main problems is how hard and confusing it is to work with different timezones.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To parse the input 09-23-2019 10:03:11 pm you can use a DateTimeFormatter and parse it to a LocalDateTime - the input has no timezone information, so we consider only the date and time, and then we can convert it to a timezone.
// parse the input
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// parse AM/PM and am/pm
.parseCaseInsensitive()
// input pattern
.appendPattern("MM-dd-yyyy hh:mm:ss a")
// use English locale for am/pm symbols
.toFormatter(Locale.ENGLISH);
LocalDateTime dt = LocalDateTime.parse("09-23-2019 10:03:11 pm", fmt);
// convert to Hawaii timezone
ZonedDateTime hawaiiDate = dt.atZone(ZoneId.of("US/Hawaii"));
The most recent JDBC drivers have support to the new API (but only for Java 8, I guess), but if you still need to work with Calendar, you can easily convert a ZonedDateTime to it:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("US/Hawaii"));
calendar.setTimeInMillis(hawaiiDate.toInstant().toEpochMilli());
In Java 8, you can also do:
Calendar calendar = GregorianCalendar.from(hawaiiDate);
If you need interoperability with the old Calendar and Date API's, you can use the new API internally to do the calculations and convert from/to the API's when needed.
According to SimpleDateFormat, I think your formatting string is wrong. You can also see in the returned value that the month, and day are wrong. MONTH=11,DAY_OF_MONTH=29
This is what you currently have:
23-SEP-19 10.03.11.000000 PM -05:00
I think the formatting string should be: 'dd-MMM-yy hh.mm.ss.SSSSSS a Z'
It also looks like the timezone issue could be because there is a colon inside it. The documentation for SimpleDateFormat indicates it needs to be in this format instead for a RFC 822 time zone: -0500 You may find it easier to use the General time zone component instead.

How to transfer GMT Date to Local Date

I have got a String of Date which has the nonstandard GMT format, like "2016-08-31T02:04:58.893GMT".
Now I need to transfer it to Local time format, like "2016-08-31 10:04:58". By the way, I am in China, there's 8 hours between the Local time and GMT time.
Oh, I use Java. Thank everyone.
You parse the string using DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz").
Example code, showing intermediate results:
String input = "2016-08-31T02:04:58.893GMT";
DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
ZonedDateTime zdtGMT = ZonedDateTime.parse(input, fmt1);
System.out.println(zdtGMT); // prints 2016-08-31T02:04:58.893Z[GMT]
ZonedDateTime zdtChina = zdtGMT.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
System.out.println(zdtChina); // prints 2016-08-31T10:04:58.893+08:00[Asia/Shanghai]
LocalDateTime ldt = zdtChina.toLocalDateTime();
System.out.println(ldt); // prints 2016-08-31T10:04:58.893
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(ldt.format(fmt2)); // prints 2016-08-31 10:04:58
You'd better transform the non-standard GMT format to a standard time format and then use some proper built-in function to add or subtract a difference. You may use another function to transform the standard time format to your designated format.
This will be great because you don't have to consider the complicated cases, for example, "2016-12-31 23:00" + 8hrs.

Joda DateTime,, Formatting, and Mysql Timestamp

After a week of going through so many examples, and moving from Java Date,
to Calendar, to Joda. I have decided to seek help from other sources.
The problem:
Our table has two fields Date (Timestamp), and TZ (String). The idea is to store
the user's UTC in timestamp, and timezone, well, you get the idea. So basically
we think in UTC, and present the user with the time converted to their
timezone on the front end (ie, using the value store in table.TZ)
Another requirement is to use the proper Object (Date, DateTime whatever).
And not pass a String representation of the date around. The best would
be a valid Long that will be correctly translated by MySQL, without having
to use the FROM_UNIXTIME mysql function in our query.
Code we are using:
public DateTime convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withLocale(l);
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
System.out.println(formatter.print(dstDateTime));
System.out.println(formatter.parseDateTime(dstDateTime.toString()));
return formatter.parseDateTime(formatter.print(dstDateTime));
}
The String output is exactly what we need (ie UTC time, 2013-08-23 18:19:12),
but the formatter.parseDateTime(dstDateTime.toString() is crashing with the following
error. Probably because of the UTC timezone independent info, and milleseconds?:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2013-08- 23T18:19:12.515Z" is malformed at "T18:19:12.515Z"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
at com.example.business.rate.RateDeck.convertTimezone(RateDeck.java:75)
at com.example.business.rate.RateDeck.WriteData(RateDeck.java:143)
at com.example.business.rate.RateDeck.main(RateDeck.java:64)
Search engine enriched question:
How to format UTC for Joda DateTime.
PS My first SO post, and it feels nice? :)
Thanks in Advance,
The new fixed version:
public Timestamp convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
return new Timestamp(dstDateTime.getMillis());
}
Nick.
It's simply crashing because the format of the parsed string doesn't match with the format of the formatter.
The formatter parses using the format yyyy-MM-dd HH:mm:ss, and the toString() method of DateTime formats the date it using (as documented) the ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ).

How can I get the current time in particular format, for a particular zone?

I want to get the current DateTime in a zone of my choice and in a particular format (eg HH-MM-SS, MM-DD-YY, MoMo-DD-YY-HH-MM-SS etc).
How can I do this, using JodaTime?
Given that you've already seen the user guide (which includes sections on time zones and formatting), it's not really clear where your confusion is. Some sample code to get you going:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime currentTimeInLondon = new DateTime(zone);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss, MM-dd-yyyy");
String text = formatter.print(currentTimeInLondon); // e.g. 08:24:54, 09-26-2012
It would be worth you taking some time to analyze why you couldn't get to this code yourself, given the information in the user guide. Being able to work out how to use APIs is a very important skill as a software engineer - you mustn't expect to be spoonfed code all the time.
this may help you.
http://joda-time.sourceforge.net/userguide.html
Use following code to get time according to particular zone with format.
Locale locale = Locale.FRENCH;
// Format with a custom format
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
String s = formatter.format(new Date());
// mar., 29 sept. 2012
// Format with a default format
s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
// 29 sept. 2012

Categories