convert String to Util date in "dd-MMM-yyyy" fromat [duplicate] - java

This question already has answers here:
How to convert a String to a Date using SimpleDateFormat?
(10 answers)
Closed 7 years ago.
I am working in Eclipse .
I have string date = "12-DEC-2016"
now i want to convert it into util date in same format. Please help me with this query.

Conversion
To convert a String into a java.util.Date of a specific format, you can use a java.text.DateFormat. DateFormat objects can perform conversions in both directions, from String to Date by calling format() and from Date to String by calling parse(). DateFormat objects can be obtained in multiple ways, here are some:
Obtain an instance via one of the static get*Instance() methods in DateFormat. This is especially useful when you want the format to be in the user's locale. For example, DateFormat.getDateInstance(DateFormat.SHORT).
Create your very own specific format by creating an instance of SimpleDateFormat. For example, new SimpleDateFormat("dd-MMM-yyyy")
You should consider whether you need a particular fixed format or whether you need the format of whatever the user's locale uses. Keep in mind that different countries use different formats.
In case the format is not for a user, but for machine to machine data interchange, you should consider using ISO 8601 or RFC 1123 as a format.
Also consider using the java.time package instead of java.util.Date. The java.time package is more powerful in case you need to perform calculations. It usually leads to code which is easier to understand and more precise, especially regarding the handling of time zones, daylight savings, local time vs. UTC and such.
Notes:
That you're working in Eclipse doesn't matter to the problem.
References
ISO 8601 https://en.wikipedia.org/wiki/ISO_8601
RFC 1123 https://www.ietf.org/rfc/rfc1123.txt
DateFormat https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html
SimpleDateFormat https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Java 8 java.time package https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

java.time
The accepted Answer by Hujer is correct but focuses on the troublesome outmoded classes of java.data.Date/.Calendar & SimpleDateFormat. As suggested, you should be using the java.time framework built into Java 8 and later.
LocalDate
The new classes include LocalDate to represent a date-only value, without time-of-day or time zone.
Parsing requires a Locale when your string includes words to be translated, name of day or month. Better to specify explicitly than depend on JVM’s current default Locale.
String input = "12-DEC-2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-MM-uuuu" );
f = f.withLocale( Locale.ENGLISH );
LocalDate ld = LocalDate.parse( input , f );

Related

What is the correct formatting pattern for this String format? [duplicate]

This question already has answers here:
Converting ZonedDateTime to string
(2 answers)
Closed 2 years ago.
I am getting a DateTimeParseException when trying to convert a String to a ZonedDateTime with threeten. I am not sure what the correct formatting pattern is for this String format?
2014-04-16T00:00+02:00[Europe/Berlin]. Can someone tell me how the correct pattern is?
On a sitenote: Is there some page or some resource somewhere where I can look such things up without having to reconstruct it by myself?
Thanks!
No formatter needed: Your format is the default format for a ZonedDateTime. ZonedDateTime both parses and prints this format as its default, that is, without any explicit formatter.
String s = "2014-04-16T00:00+02:00[Europe/Berlin]";
ZonedDateTime zdt = ZonedDateTime.parse(s);
System.out.println("Parsed into " + zdt);
Output:
Parsed into 2014-04-16T00:00+02:00[Europe/Berlin]
The format is extended from ISO 8601 format. ISO 8601 would be 2014-04-16T00:00+02:00 only, so includes the UTC offset but not the time zone. The developers of java.time extended it to include the time zone ID.
If you want a formatter: If you have a special reason for wanting a formatter, maybe you need to pass one to a method or you just wish to make it explicit which format you expect, one is built in: DateTimeFormatter.ISO_ZONED_DATE_TIME. So you still don’t need to write any format pattern string.
Where to find this information? It’s in the documentation of the classes of java.time. See the documentation links below.
Your own code: Thank you for providing your own code in the comment under this answer. For other readers I am repeating it here, formatted for readability.
fun parseZonedDateTimeToString(date: ZonedDateTime): String {
return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(date)
}
fun parseStringToZonedDateTime(dateString: String): ZonedDateTime {
return ZonedDateTime.parse(dateString, DateTimeFormatter.ISO_ZONED_DATE_TIME)
}
Links
Wikipedia article: ISO 8601
Documentation links:
The one-arg ZonedDateTime.parse() specifying “a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris]”
ZonedDateTime.toString() promising “a String, such as 2007-12-03T10:15:30+01:00[Europe/Paris]”
DateTimeFormatter with the built-in formatters as well as the pattern letters used in format pattern strings
DateTimeFormatter.ISO_ZONED_DATE_TIME, “The ISO-like date-time formatter that formats or parses a date-time with offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.”
Since the links above are to the documentation of the Java 10 versions of the classes, which is not always identical to the documentation of the backport, here is the documentation of ThreeTen backport 1.4.2 API, under which you will find all of the above items too.

SimpleDateFormat doesn't give me the pattern I need

I'm having a problem with SimpleDateFormat. I have inputfields in my HTML-page with type = date. I want to save these values into my database where they should be saved as dates. I already figured out how to do this and it works. The only probem I encouter is the way the dates are represented in the database.
I want them to be representated as dd-MM-yyyy. Let's say I want to display 01-06-2016 into my database. When doing this with the code I have..it gives me 0006-12-07. Strangely..when I change my pattern into yyyy-MM-dd...it does give me exactly what the pattern says: 2016-06-01. But it doesn't work the other way round.
String parameter = request.getParameter("instroomdatum");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
Date parsed = sdf.parse(parameter);
java.sql.Date sql = new java.sql.Date(parsed.getTime());
student.setInstroomdatum(sql);
} catch (ParseException ex) {
Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
}
Can somebody please explain me what's going on and how to fix this problem? It's really annoying.
EDIT: I tried printing the value of parameter with a simple PrintWriter-object for the specific date 01-06-2016. It shows me 2016-06-01, even though my pattern in the code above is set to dd-MM-yyyy.
You are confusing the display format with the internal representation.
Dates in a database are not represented in any specific display format, such as YYYY-MM-DD. Database dates are normally stored in a numeric form that represents a certain number of seconds and milliseconds (or nanoseconds) from some fixed starting point.
The display format is applied dynamically when you query the database and ask for the date/time as a string, but if you ask for it as a Date object, you get the internal representation, encapsulated in a java.sql.Date.
It is up to your Java code to format the date as you need it.
In your particular example (according to your comment), the string returned by your input method is 2016-06-01, so you need to parse it with the pattern yyyy-MM-dd. This will correctly convert the external representation to a valid Date object.
But how should i specifically change this representation to dd-MM-yyyy
Once you have it as Date, you can immediately turn around and convert the Date back into a String with a different SimpleDateFormat specification.
Date-Time != String
As explained in the correct Answer by Garrison, you must understand that a date’s value internally in a database or in a language such as Java is distinct is distinct from a String generated to represent or communicate that value.
How the date is internally tracked varies amongst databases and languages, and is irrelevant really. What matters is the interface provided by which you can fetch or put your app’s values. A separate issue is how to represent those values as Strings for presentation to your user.
Database (internal) ↔ Driver (JDBC) ↔ App (java.time) ↔ Presentation (String)
java.time
Also, the Question and the other Answers are using old outmoded classes, the date-time classes bundled with the earliest versions of Java. Those classes have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDate
Amongst the java.time classes is LocalDate to represent a date-only value without time-of-day and without time zone. The old java.util.Date class, despite its unfortunate name, tracks both a date and a time-of-day. The old java.sql.Date pretends to represent a date-only but in fact, in an unfortunate design decision, extends from java.util.Date so it inherits both a date and a time-of-day, but you are instructed in the class doc to pretend that it is not a subclass. (yes, that is an unpleasant mess)
Do all your business logic using the java.time classes such as LocalDate.
Strings & ISO 8601
As for strings, use the standard ISO 8601 formats. For serializing date-only values, that means YYYY-MM-DD. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values.
LocalDate localDate = LocalDate.parse( "2016-06-01" );
But try to stick with objects. Serialize to strings only when you must.
Database
No need for strings when getting data to/from a database. The job of a JDBC driver is to figure out how to move a Java object to/from a data type of your database column.
With a driver that complies with JDBC 4.2, you should be able to use the getObject and setObject methods on a PreparedStatement to deal directly with java.time types.
myPreparedStatement.setObject( 1 , localDate );
If your driver does not support that, you must fall back onto the java.sql.Date class. Look for new methods added to the old classes to go back and forth with java.time types.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
And the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Generate Strings
Apply a format to generate a string as needed for presentation to a user. Use the DateTimeFormatter class. You can define your own formatting pattern.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MM-yyyy" );
String output = localDate.format( formatter ); // 01-06-2016
Better yet, let java.time localize to the human language and cultural norms of the user’s desired/expected Locale.
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT , locale );
String output = localDate.format( formatter );
You will need to use the formatter to generate a String for presentation to the user, and to parse input made by the user. You or your users may wish instead to take data-entry as three separate fields: year, month, and day-of-month.
LocalDate localDate = LocalDate.of( 2016 , 6 , 1 );
If all you want to do is format your date into 01-06-2016 format. Try this
String parameter = "0006-12-07";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parsed = sdf.parse(parameter);
sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(sdf.format(parsed)); //Prints out your desired format 07-12-0006
java.sql.Date sql = new java.sql.Date(parsed.getTime());
student.setInstroomdatum(sql);
} catch (ParseException ex) {
Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE,null, ex);
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date someDate;
Date anotherDate = format.parse(/*needVariables*/.getOutDate());
someDate = new java.sql.Date(anotherDate.getTime());
work for me

Formatting java.time Instant values from PostgreSQL Timestamp values

I'm new to the java.time formats in Java 8 and later, but I'm reasonably comfortable with Joda-Time and I'm very familiar with Java's java.util.Date, java.util.Calendar, and DateFormat classes along with ISO 8601.
I'm using PostgreSQL 9.3 with jOOQ 3.6.4, with a foo table column containing a timestamp:
bar timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP
I retrieve that bar value using jOOQ, and try to print it out using java.time's DateTimeFormatter.ISO_OFFSET_DATE_TIME:
DateTimeFormatter timestampFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
Cursor<FooRecord> fooRecordCursor = createDSLContext().selectFrom(FOO).fetchLazy();
for(FooRecord fooRecord : fooRecordCursor) {
System.out.println(timestampFormatter.format(fooRecord.getBar().toInstant());
}
This throws an UnsupportedTemporalTypeException:
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year
at java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext$1.getLong(DateTimePrintContext.java:205)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
But if I use my own custom ISO8601DateFormat which extends the old-school SimpleDateFormat, I can parse the value just fine:
final DateFormat timestampFormatter = new ISO8601DateFormat();
...
System.out.println(timestampFormatter.format(fooRecord.getBar());
I find this very confusing:
The jOOQ bar field accessor returns a java.sql.Timestamp. In the Java 8 version I convert that to an Instant, but why would that reduce the amount of information available?
An Instant is supposed to be an absolute point of time --- isn't it simply based upon a long offset just like JodaTime and Java Date?
Why is DateTimeFormatter.ISO_OFFSET_DATE_TIME expecting a Year field from an Instant? Shouldn't the formatter just convert the long offset to a date/time in the current time zone, and retrieve the year from that? I wouldn't expect any instant to contain a Year field.
In short: If my SimpleDateFormat-based ISO8601DateFormat works fine for a Timestamp from PostgreSQL, why can't DateTimeFormatter.ISO_OFFSET_DATE_TIME figure out how to format the Instant version of the same value?
Short answer:
It's because the java.time classes are separating the concepts "point in time" and "time as a human sees it" whereas Timestamp/Date don't.
Long answer:
You are right, an Instant is representing a single point in the time line. That's why it is not possible to give a correct/unique answer to the question "what's the year/day/time?". It depends on where on the world the question is asked: In New York it differs from Sidney.
But your DateTimeFormatter is asking exactly this question. And that is why you get an UnsupportedTemporalTypeException.
Date and its subclass Timestamp on the other hand are mixing up the two concepts. While internally storing a long "point in time", they "answer" if asked for their year. Usually they are assuming the local time zone of the system to pin the the long-offset to an specific time zone.
This is error-prone and let to introduction of Calendar, JodaTime and java.time.
Now, why is your DateTimeFormatter not smart enough to align Instant to the default TimeZone?
DateTimeFormatter works on the TemporalAccessor interface and does not differ between concrete implementations like Instant, LocalDateTime or ZonedDateTime. There are legitimate formatting cases for all of those implementations and I assume it is simply not feasible to check the concrete object's compatibility with the given format let alone to perform correct conversions.
The solution:
You have to align your timestamp to a timezone/offset yourself:
System.out.println(timestampFormatter.format(
fooRecord.getBar().toLocalDateTime().atZone(ZoneId.systemDefault()));

Converting a time String to ISO 8601 format

I am trying to create a String in a format like 2015-08-20T08:26:21.000Z
to 2015-08-20T08:26:21Z
I know it can be done with some String splitting techniques, but i am wondering if there is an elegant solution for that (with minimal code changes).
Both of the above are time strings, the final one which i need is Date in ISO 8601 . https://www.rfc-editor.org/rfc/rfc3339#section-5.6
I have tried a few similar questions like converting a date string into milliseconds in java but they dont actually solve the purpose.
Also tried using :
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());
But it still does not do any String to String conversions. Getting the following error:
23:04:13,829 WARN [RuntimeExceptionMapper] caught RuntimeException: {}: java.lang.IllegalArgumentException: Cannot format given Object as a Date
Is there some library which someone can suggest ?
Thanks.
tl;dr
Instant.parse( "2015-08-20T08:26:21.000Z" )
.toString()
2015-08-20T08:26:21Z
Date-Time Formatter
If all you want to do is eliminate the .000, then use date-time objects to parse your input string value, then generate a new string representation of that date-time value in a different format.
ISO 8601
By the way, if that is your goal, the Question’s title make no sense as both strings mentioned in the first sentence are valid ISO 8601 formatted strings.
2015-08-20T08:26:21.000Z
2015-08-20T08:26:21Z
java.time
Java 8 and later has the new java.time package. These new classes supplant the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes. Those old classes were confusing, troublesome, and flawed.
Instant
If all you want is UTC time zone, then you can use the Instant class. This class represents a point along the timeline without regard to any particular time zone (basically UTC).
DateTimeFormatter.ISO_INSTANT
Calling an Instant’s toString generates a String representation of the date-time value using a DateTimeFormatter.ISO_INSTANT formatter instance. This formatter is automatically flexible about the fractional second. If the value has a whole second, no decimal places are generated (apparently what the Question wants). For a fractional second, digits appear in groups of 3, 6, or 9, as needed to represent the value up to nanosecond resolution. Note: this format may exceed ISO 8601 limit of milliseconds (3 decimal places).
Example code
Here is some example code in Java 8 Update 51.
String output = Instant.parse( "2015-08-20T08:26:21.000Z" ).toString( );
System.out.println("output: " + output );
output: 2015-08-20T08:26:21Z
Changing to a fractional second, .08
String output = Instant.parse( "2015-08-20T08:26:21.08Z" ).toString( );
output: 2015-08-20T08:26:21.080Z
If interested in any time zone other than UTC, then make a ZonedDateTime object from that Instant.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , ZoneId.of( "America/Montreal" ) ) ;
Your format is just not right try this :-
try {
String s = "2015-08-20T08:26:21.000Z";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date d = df.parse(s);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
System.out.println(sdf.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
Conversion of a date String of unknown formatting into a date String that uses known formatting can be accomplished using two DateFormat objects- one dynamically configured to parse the format of the input String, and one configured to generate the formatted output String. For your situation the input String formatting is unspecified and must be provided by the caller, however, the output String formatting can be configured to use ISO 8601 formatting without additional input. Essentially, generating an ISO 8601 formatted date String output requires two inputs provided by the caller- a String containing the formatted date and another String that contains the SimpleDateFormat format.
Here is the described conversion as Java code (I deliberately have left out null checks and validations, add these as appropriate for your code):
private String formatDateAsIso8601(final String inputDateAsString, final String inputStringFormat) throws ParseException {
final DateFormat iso8601DateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.ENGLISH);
iso8601DateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
final DateFormat inputDateFormatter = new SimpleDateFormat(inputStringFormat, Locale.ENGLISH);
final Date inputDate = inputDateFormatter.parse(inputDateAsString);
return iso8601DateFormatter.format(inputDate);
}
If you want to modify that method please note that SimpleDateFormat is not thread-safe, and that you should not use it from a static context without a workaround for multi-threaded code (ThreadLocal is commonly used to do just such a workaround for SimpleDateFormat).
An additional "gotcha" is the use of a Locale during the construction of the SimpleDateFormat objects- do not remove the Locale configuration. It is not safe to allow the system to choose to use the default Locale because that is user/machine specific. If you do allow it to use the default Locale, you run the risk of transient bugs because your development machine uses a Locale different than the Locale of your end-user. You do not have to use my selected ENGLISH Locale, it is perfectly fine to use a different Locale (you should understand the rules of that Locale and modify the code as appropriate however). Specification of no Locale and utilization of the system default is incorrect however, and likely will lead to many frustrating hours trying to diagnose an elusive bug.
Please understand this solution is not ideal as of Java 8 and the inclusion of the JodaTime based classes, like Instant. I chose to answer using the outdated API's because those were what you seemed concerned with in your question. If you are using Java 8 I strongly urge to learn and utilize the new classes as they are an improvement in almost every conceivable way.

Using Joda-Time Library to Convert String to DateTime Format in Google Tasks API

I have a date/time string which needs to be sent to the Google Tasks API but I can't figure out how to convert a Joda-Time library DateTime object to a Java DateTime object. I'm using Android as the platform.
The string starts off as "2012/07/19 22:00:00" and is first converted to Iso format.
Here is my code:
Task task = new Task();
task.setTitle(title);
task.setNotes(note);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime dt = formatter.parseDateTime(dateToIso("2012/07/19 22:00:00"));
task.setDue(dt);
private String dateToIso(String date) {
date = date.replace("/", "-");
date = replaceCharAt(date, 10, 'T');
date = date + ".000Z";
return date;
}
The error I am getting is:
"Type mismatch: cannot convert from org.joda.time.DateTime to
com.google.api.client.util.DateTime"
Please assist. Information with regards to ISO conversion would also be useful.
Let Formatter Parse String
The problem is your "dateToIso" method. No need for that. The DateTimeFormatter object's job is to parse the string when given the correct format. You did indeed give it the correct format. And then you went and morphed the string into a different format!
Solution: (a) Kill your dateToIso method. (b) Delete the call to that method. Just pass the original string to parseDateTime.
Side-Problem: You ignored the issue of time zone. So when parsing that string, Joda-Time will assume the event of that date-time occurred in your JVM's default time zone. So running this same code with same inputs but on another computer/JVM with different time zone settings will result in different output. Probably not what you want. Lesson Learned: Always specify a time zone rather than rely on default.
Yet Another Problem: The error you quoted is a different problem, converting from Joda-Time to Google time. Read on.
Read The Doc
If you are trying to convert your org.joda.time.DateTime object to a com.google.api.client.util.DateTime object, just look at the JavaDoc. There you will see that the constructor of the Google DateTime takes a java.util.Date. Joda-Time has a built-in toDate method to convert to a java.util.Date object for interoperability with other classes.
Food-Chain
Create a food chain of objects like this:
org.joda.time.DateTime → java.util.Date → com.google.api.client.util.DateTime
Some untested code…
org.joda.time.DateTimeZone = org.joda.time.DateTimeZone.forID( "Africa/Johannesburg" );
org.joda.time.DateTime jodaDateTime = new DateTime( timeZone );
// Convert from Joda-Time to old bundled j.u.Date
java.util.Date juDate = jodaDateTime.toDate();
// Convert from j.u.Date to Google Date.
com.google.api.client.util.DateTime googleDateTime = new com.google.api.client.util.DateTime( juDate );
Milliseconds
Alternatively, you could extract and pass milliseconds.
Generally I recommend avoiding dealing directly with milliseconds where possible. Using milliseconds can be confusing, sloppy, and error-prone. A milliseconds count is difficult to debug as humans cannot readily decipher the date-time meaning of a long. While Joda-Time and java.util.Date use milliseconds-since-Unix-epoch as their internal time-tracking mechanism…
Some software uses seconds or nanoseconds rather than milliseconds.
Some software uses other epochs rather than the Unix epoch.
Going The Other Direction
[The following section assumes Google has supplanted the API referenced by the Question with a newer API. Not sure if this assumption is correct.]
When going from a com.google.gdata.data.DateTime object to a Joda-Time DateTime, I would use the milliseconds count-from-epoch provided by the getValue method. Note that it returns a 64-bit long, rather than a 32-bit int.
Be sure to assign the desired time zone to the Joda-Time DateTime rather than rely on implicitly assigning the JVM’s current default time zone.
long millisecondsFromUnixEpoch = myGoogleDateTime.getValue();
org.joda.time.DateTimeZone zone = DateTimeZone.forID( "Africa/Johannesburg" );
org.joda.time.DateTime jodaDateTime = new DateTime( millisecondsFromUnixEpoch, zone );
The Google API provides a few other choices.
toStringRfc822
You could call the toStringRfc822 method to generate a string to be parsed by Joda-Time. Unfortunately, RFC 822 is awkward and ambiguous to parse. Among other faults it uses the non-standard non-unique 3-4 letter time zone codes rather than proper time zone names. Joda-Time refuses to attempt parsing those codes because of their ambiguity. I assume Google only includes it here for backward-compatibility with old APIs/libraries. The modern Internet protocols have moved on to ISO 8601.
toUiString
Perhaps you could call the toUiString method to create a string to be parsed by Joda-Time. Unfortunately, their documentation fails to explain what format is used by that method.
toString
You could call the toString method that is documented as producing a xs:dateTime string. The doc fails to explain precisely, but I'm guessing they mean the XML Schema spec’s inclusion of ISO 8601. You might try this method to see what it generates. It may be useful if you want to preserve the offset-from-UTC embedded in the Google object. But remember that a time zone is more than an offset-from-UTC, so you should still assign the desired/expected time zone to your Joda-Time DateTime object. Therefore, I'm not sure if this better than just passing the long count-from-epoch to the constructor of Joda-Time DateTime.
java.time
Now that Java 8 is released, perhaps Google may modernize its APIs to use the java.time package.
Note that java.time extends the ISO 8601 format to append the formal name of the time zone, a very helpful idea.

Categories

Resources