Joda-Time: convert SimpleDateFormat pattern to DateTimeFormat.forPattern - java

I'm trying to modify some code to use Joda-Time rather than java.sql.Timestamp
Currently the code is using Threadlocal and SimpleDateFormat:
public static final ThreadLocal<DateFormat> FORMAT_TIMESTAMP = new ThreadLocal<DateFormat>() {
#Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
}
};
public static String format(Timestamp timestamp) {
return FORMAT_TIMESTAMP.get().format(timestamp);
}
My understanding is that Joda-time is thread safe, so there is no need to use ThreadLocal
With this in mind I have modified the code to this:
public static String format(Instant timestamp) {
Instant formated = Instant.parse(timestamp.toString(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssXXX"));
return formated.toString();
}
If I nned to insert the values into a DB later in the code I plan to use this method.
Assuming I'm going about this the right way, is there anyway to format the DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssXXX") like the
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
At the moment I'm getting a Invalid format Exception

X is not recognised by Joda. Replacing the XXX by ZZ should do what you need.
Because DateTimeFormat is thread safe, you can share it across threads. So your code could look like this:
private static final DateTimeFormatter FORMAT_TIMESTAMP =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");
public static String format(Instant timestamp) {
return FORMAT_TIMESTAMP.print(timestamp);
}

tl;dr
No need to define the formatting pattern for standard inputs.
Parse directly into java.time objects.
Examples…
// offset-from-UTC
OffsetDateTime.parse( "2016-01-23T12:34:56.123456789-07:00" )
…
// Z = Zulu = UTC
Instant.parse( "2016-01-23T12:34:56.123456789Z" )
…
// ISO 8601 format extended with time zone name appended in square brackets.
ZonedDateTime.parse( "2016-01-23T12:34:56.123456789-05:30[Asia/Kolkata]" )
Details
The Joda-Time project, now in maintenance mode, advises migration to java.time classes.
java.time
No need for ThreadLocal as the java.time classes are inherently thread-safe because of they are immutable objects.
The standard ISO 8601 formats for date-time values are used by default in the java.time classes. So generally no need to specify a formatting pattern for such inputs.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
The Instant.parse method can parse standard input strings ending in Z, short for Zulu, meaning UTC.
Instant instant = Instant.parse(
"2016-01-23T12:34:56.123456789Z" );
OffsetDateTime
For standard input strings that include a specific offset-from-UTC, use the OffsetDateTime class and its parse method.
OffsetDateTime odt = OffsetDateTime.parse(
"2016-01-23T12:34:56.123456789-07:00" );
ZonedDateTime
The ZonedDateTime class with its toString method generates a String in a format that extends beyond the ISO 8601 format by appending the name in square brackets. This is wise, as a time zone is much more than an offset-from-UTC. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
This class can parse as well as generate such strings.
ZonedDateTime zdt = ZonedDateTime.parse(
"2016-01-23T12:34:56.123456789-05:30[Asia/Kolkata]" ) ;
DateTimeFormatter
For non-standard string formats, search Stack Overflow for java.time.format.DateTimeFormatter class.
Database
To send this value to a database through a JDBC driver supporting JDBC 4.2 or later, use the PreparedStatement::setObject method and for fetching, the ResultSet::getObject method.
myPreparedStatement.setObject( … , instant );
If your driver does not comply, fall back to converting to the old java.sql types. Look to the new conversion methods added to the old classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Epoch Timestamp String to Joda Datetime using ONLY String Formatter

Assuming I have a timestamp "1355409000003" as a String, is there a way to specify a DateTime format that parses that into a Joda DateTime?
I.e., I can parse "12/01/2012" with format "MM/dd/YYYY" and "2012-12-01 04:27" with "YYYY-MM-dd HH:mm", but how can I parse "1355409000003"?
edit: not using a different constructor, assume I MUST specify a String format to parse with
tl;dr
Just parse your String to long. No big deal.
Use java.time classes that supplant Joda-Time project.
Instant.ofEpochMilli(
Long.parseLong( "1355409000003" )
)
2012-12-13T14:30:00.003Z
Parse String to long
Your Question does not really make sense. If you get a string representing the count of milliseconds since epoch of 1970-01-01T00:00Z, then convert that String to a long and pass to the constructor of the Joda-Time DateTime type.
This was shown in an Answer that was inexplicably deleted.
DateTime dt = new DateTime( Long.parseLong( "1355409000003" ) ) ;
Or, personally, I would separate onto two lines.
long millisSinceEpoch = Long.parseLong( "1355409000003" ) ;
DateTime dt = new DateTime( millisSinceEpoch ) ;
You posted this Comment to that Question:
unfortunately, the structure by which these timestamps are being consumed does not lend itself to using a different constructor - assuming I am REQUIRED to specify a string format, is there a format that parses epoch timestamps?
Again, your insistence on a constructor taking a String is nonsensical, as it is simple to the point of being trivial to wrap your textual number with a parsing call: Long.parseLong( "1355409000003" ). Don’t make a mountain out of a molehill.
java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Same approach here with java.time as seen above with Joda-Time: Parse the String to a long, and use the number to get an Instant object (rather than a DateTime object).
The java.time classes avoid constructors. So, instead of calling a constructor, call the static factory method Instant.ofEpochMilli.
long millisSinceEpoch = Long.parseLong( "1355409000003" ) ;
Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;
Custom method
If the issue prompting your insistence is that this occurs throughout your code, and you want to avoid littering your codebase with all the extra Long.parseLong(, then you could make your own utility method to encapsulate this string-to-long conversion.
I am not recommending this as it seems like overkill. But if you insist, here is some example code.
package com.basilbourque.example;
import java.time.Instant;
public class InstantMaker
{
static public Instant parseMillis ( String countOfMillisecondsSinceEpoch )
{
// TODO - Add code to test for invalid inputs, trap for exception thrown.
long millis = Long.parseLong( countOfMillisecondsSinceEpoch );
Instant instant = Instant.ofEpochMilli( millis);
return instant;
}
// Constructor. Hide the default constructor as "private". We have no need for instances here.
private InstantMaker ( )
{
}
// `main` method for testing ad demonstration.
public static void main ( String[] args )
{
Instant instant = InstantMaker.parseMillis( "1355409000003" );
System.out.println( instant );
}
}
If this is your concern, I suggest the real problem is relying on a count-from-epoch regardless of whether it is textual or numeric. A count-from-epoch makes date-time handling much more difficult as the values cannot be discerned by humans. This makes troubleshooting, debugging, and logging tricky and unnecessarily complicated. I would suggest refactoring your code to be passing around Instant instances rather than strings like "1355409000003".
ISO 8601
If you must serialize date-time values to text, use only the standard ISO 8601 formats. That is the primary purpose for the standard, exchanging date-time values between systems. The formats are designed to be practical and sensible, easy to parse by machine yet easy to read by humans across cultures.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings. You can see examples of such strings above in this Answer.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java Date Format Parsing

I am trying to change the date format from a JSON response, but I keep getting java.text.ParseException.
This is the date from the server 2015-02-03T08:37:38.000Z and I want it to show as 2015/02/03 That's yyyy-MM-dd. And I did this.
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
String dateResp = transactionItem.get(position).getDate();
try {
Date date = df1.parse(dateResp);
transDate.setText(dateFormatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
But the exception keeps showing.
You must escape the Z:
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Try to use this for formatting purpose instead of your provided formatting string. It should work nicely :)
tl;dr
Instant.parse( "2015-02-03T08:37:38.000Z" )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.toString() // 2015-02-03
Using java.time
The modern way to handle date-time work is with the java.time classes.
Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.
Parse that string as an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2015-02-03T08:37:38.000Z" ) ;
To extract a date, you must specify a time zone. For any given moment the date varies around the globe by zone. For example, a moment after midnight in Paris France is a new day while still “yesterday” in Montréal Canada.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You want only the date portion without the time of day. So extract a LocalDate. While a LocalDate lacks any concept of offset-from-UTC or time zone, the toLocalDate method respects the ZonedDateTime object’s time zone in determining the date.
LocalDate ld = zdt.toLocalDate();
You seem to want standard ISO 8601 format, YYYY-MM-DD. Simply call toString without need to specify a formatting pattern.
String output = ld.toString();
2015-02-03
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

How to get timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Timestamp());
This is what I have, but Timestamp() requires an parameters...
Replace
new Timestamp();
with
new java.util.Date()
because there is no default constructor for Timestamp, or you can do it with the method:
new Timestamp(System.currentTimeMillis());
Use java.util.Date class instead of Timestamp.
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
This will get you the current date in the format specified.
tl;dr
Use only modern java.time classes. Never use the terrible legacy classes such as SimpleDateFormat, Date, or java.sql.Timestamp.
ZonedDateTime // Represent a moment as perceived in the wall-clock time used by the people of a particular region ( a time zone).
.now( // Capture the current moment.
ZoneId.of( "Africa/Tunis" ) // Specify the time zone using proper Continent/Region name. Never use 3-4 character pseudo-zones such as PDT, EST, IST.
) // Returns a `ZonedDateTime` object.
.format( // Generate a `String` object containing text representing the value of our date-time object.
DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" )
) // Returns a `String`.
Or use the JVM’s current default time zone.
ZonedDateTime
.now( ZoneId.systemDefault() )
.format( DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" ) )
java.time & JDBC 4.2
The modern approach uses the java.time classes as seen above.
If your JDBC driver complies with JDBC 4.2, you can directly exchange java.time objects with the database. Use PreparedStatement::setObject and ResultSet::getObject.
Use java.sql only for drivers before JDBC 4.2
If your JDBC driver does not yet comply with JDBC 4.2 for support of java.time types, you must fall back to using the java.sql classes.
Storing data.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , odt ) ;
Retrieving data.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
The java.sql types, such as java.sql.Timestamp, should only be used for transfer in and out of the database. Immediately convert to java.time types in Java 8 and later.
java.time.Instant
A java.sql.Timestamp maps to a java.time.Instant, a moment on the timeline in UTC. Notice the new conversion method toInstant added to the old class.
java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Instant instant = ts.toInstant();
Time Zone
Apply the desired/expected time zone (ZoneId) to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Formatted Strings
Use a DateTimeFormatter to generate your string. The pattern codes are similar to those of java.text.SimpleDateFormat but not exactly, so read the doc carefully.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" );
String output = zdt.format( formatter );
This particular format is ambiguous as to its exact meaning as it lacks any indication of offset-from-UTC or time zone.
ISO 8601
If you have any say in the matter, I suggest you consider using standard ISO 8601 formats rather than rolling your own. The standard format is quite similar to yours. For example:2016-02-20T03:26:32+05:30.
The java.time classes use these standard formats by default, so no need to specify a pattern. The ZonedDateTime class extends the standard format by appending the name of the time zone (a wise improvement).
String output = zdt.toString(); // Example: 2007-12-03T10:15:30+01:00[Europe/Paris]
Convert to java.sql
You can convert from java.time back to java.sql.Timestamp. Extract an Instant from the ZonedDateTime.
New methods have been added to the old classes to facilitate converting to/from java.time classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You can make use of java.util.Date instead of Timestamp :
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
Use modern java.time classes if you use java 8 or newer.
String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat.
You can use the following:
new java.sql.Timestamp(System.currentTimeMillis()).getTime()
Result:
1539594988651
A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());
I am Using this
String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);

Convert date or calendar type into string format

So, basically I am trying to achieve the following format in a String:
2012-06-17T08:00:00.000+01:00
I get the original date in a string format which I then parse into different formats.
When I use SimpleDateFormat with the format as (yyyy-MM-dd'T'HH:mm:ss.sssZ), I get the following output:
2013-06-17T07:00:00.000+0530
Here +0530 should be +05:30
When I set the above date into a Calendar type and then convert it to a string I get the following format:
2013-06-17T07:00:00+05:30
Here I don't get the .000 after the seconds.
Any ideas how this can be achieved, without using JodaTime. Need manipulations in Date, String and Calendar type only
Firstly to get the extra : use XXX in your formatter like so and use Uppercase S to get the milliseconds
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
UPDATE: Above doesn't work on 1.6
Yo could try the following however
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
{
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
{
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length()-2, ':');
};
See this post for more
SimpleDateFormat pattern
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
tl;dr
OffsetDateTime.parse( "2012-06-17T08:00:00.000+01:00" ) // Parse string in standard ISO 8601 format to an object.
.format( // Generate a String representing the value of that `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX" ) // Specify a formatting pattern to force the seconds and fractional second even if zero.
) // Return a `String` object.
2012-06-17T08:00:00.000+01:00
java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Avoid Date, Calendar, and SimpleDateFormat.
ISO 8601
Your desired format happens to be standard ISO 8601 format. The java.time classes use the standard format by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime
Your input string includes an offset-from-offset but not a time zone. So we parse as a OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2012-06-17T08:00:00.000+01:00" ) ;
To generate a string in the same standard ISO 8601 format, simply call toString. By default, the least significant parts are omitted if zero. So no seconds or fractional second appear using your example data.
String output = odt.toString() ;
2012-06-17T08:00+01:00
If you want to force the seconds and fractional second even when zero, specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2012-06-17T08:00:00.000+01:00" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX" );
String output = odt.format( f );
2012-06-17T08:00:00.000+01:00
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Creating Java Calendar, basic parameters

I would like to send a Java Calendar object over a web service (soap). I notice that this kind of object is too complex and there should be a better method to send the same information.
What are the basic attributes that should be sended over the web service, so the client can create a Java Calendar out of this attributes?
I'm guessing: TimeZone, Date, and Time?
Also, how can the client recreate the Calendar based on those attributes?
Thanks!
In fact I would go for Timezone tz (timezone the calendar was expressed in), Locale loc (used for data representation purpose) and long time (UTC time) if you want exactly the same object.
In most uses the time is enough though, the receiver will express it with his own timezone and locale.
I suppose the Calendar instance that you would like to send is of type java.util.GregorianCalendar. In that case, you could just use xsd:dateTime. For SOAP, Java will usually bind that to a javax.xml.datatype.XMLGregorianCalendar instance.
Translating between GregorianCalendarand XMLGregorianCalendar:
GregorianCalendar -> XMLGregorianCalendar: javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar(GregorianCalendar)
XMLGregorianCalendar -> GregorianCalendar: XMLGregorianCalendar.toGregorianCalendar()
The easiest way is to use a long value.
java.util.Calendar.getInstance().getTimeInMillis()
This returns the long value for the date. That value can be used to construct java.util.Date or a Calendar.
tl;dr
Use plain text, in UTC, in standard ISO 8601 format.
Instant.now().toString()
2018-01-23T01:23:45.123456Z
Instant.parse( "2018-01-23T01:23:45.123456Z" )
ISO 8601
The ISO 8601 standard is a well-designed practical set of textual formats for representing date-time values.
2018-01-14T03:57:05.744850Z
The java.time classes use these standard formats by default when parsing/generating strings. The ZonedDateTime class wisely extends the standard to append the name of a time zone in square brackets.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
String output = zdt.toString() ;
2018-01-13T19:56:26.318984-08:00[America/Los_Angeles]
java.time
The java.util.Calendar class is part of the troublesome old date-time classes bundled with the earliest versions of Java. These legacy classes are an awful mess, and should be avoided.
Now supplanted by the modern industry-leading java.time classes.
UTC
Generally best to communicate a moment using UTC rather than a particular time zone.
The standard format for a UTC moment is YYYY-MM-DDTHH:MM:SS.SSSSSSSSSZ where the T separates the year-month-day from the hour-minute-second. The Z on the end is short for Zulu and means UTC.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;
String output = instant.toString() ;
2018-01-14T03:57:05.744850Z
If a particular time zone is crucial, use a ZonedDateTime as shown above.
Parsing
These strings in standard format can be parsed to instantiate java.time objects.
Instant instant = Instant.parse( "2018-01-14T03:57:05.744850Z" ) ;
ZonedDateTime zdt = ZonedDateTime.parse( "2018-01-13T19:56:26.318984-08:00[America/Los_Angeles]" ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time (JSR 310) classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories

Resources