Using an offset for a date that isn't today - java

I did a lot of searches trying to find this solution. Messing with dates in Java gives me a headache. Most of the results I found were using math to find a previous date or about finding a date offset from today's date. I really needed something from a predefined date (not today). I messed with a lot of classes and code before finding what I needed.
This is also my first post here. I'm a veteran lurker. I hope this saves someone the time I took to find this.
Submit date Dec 2, 2014 and find the date from the week before.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class FilenameDateFormat {
SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyyMMdd");
public static void main(String[] args) throws ParseException {
new FilenameDateFormat("20141202", -7);
}
public FilenameDateFormat(String dateArg, int offsetDays) throws ParseException {
Date fileDate = fileDateFormat.parse(dateArg);
Calendar cal = new GregorianCalendar();
cal.setTime(fileDate);
cal.add(Calendar.DAY_OF_MONTH, offsetDays);
System.out.println(cal.getTime());
}
}
RESULT
Tue Nov 25 00:00:00 EST 2014

Why dont you use new java.time api ? This could be easily acomplished in java8.
https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

tl;dr
LocalDate.parse(
"20141202" ,
DateTimeFormatter.BASIC_ISO_DATE
).minusWeeks( 1 )
2014-11-25
Avoid legacy date-time classes
Messing with dates in Java gives me a headache.
Date-time work in general is tricky, slippery, elusive.
And using the troublesome old date-time classes (java.util.Date, java.util.Calendar, etc.) makes the work all the more difficult. Those old classes are now legacy, supplanted by the java.time classes.
LocalDate
Submit date Dec 2, 2014
The LocalDate class represents a date-only value without time-of-day and without time zone.
Your input string happens to be in the “basic” version of the standard ISO 8601 format. The canonical version includes hyphens, 2014-12-02, while the “basic” version minimizes the use of separators, 20141202. I strongly suggest using the fuller version when possible to improve readability and reduce ambiguity/confusion.
DateTimeFormatter
The DateTimeFormatter class includes a pre-defined formatting pattern for your input, DateTimeFormatter.BASIC_ISO_DATE.
String input = "20141202" ;
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = LocalDate.parse( input , f );
In real code, trap for the DateTimeParseException being thrown because of bad input.
String input = "20141202" ;
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = null;
try{
ld = LocalDate.parse( input , f );
} catch ( DateTimeParseException e ) {
… // Handle error because of bad input.
}
Subtracting a week
find the date from the week before
Subtract a week. Note that java.time uses immutable objects. So rather than alter (mutate) the values in an object, we generate a new and separate object based on the original’s values.
LocalDate oneWeekAgo = ld.minusWeeks( 1 );
input: 20141202
ld.toString(): 2014-12-02
oneWeekAgo.toString(): 2014-11-25
See live code in IdeOne.com.
If you want a String in the same format as the input, use the same formatter seen above.
String output = oneWeekAgo.format( DateTimeFormatter.BASIC_ISO_DATE );
20141125
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.

Related

How to Convert a Date time value with UTC offset into GMT in java 7

I have a date time value 2016-12-21T07:48:36 with an offset of UTC+14. How to convert the datetime into equivalent standard GMT time.
I tried with sampleDateFormat.parse() method.But, I am not able to get the TimeZone object for UTC offset like.
sampleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC+14:00"))
Please help me to convert the UTC datetime into standard GMT time in Java 7.
I will assume you have the original date as a string. Do the following:
Create a SimpleDateFormat and set the timezone to "GMT+14"
Parse the string value. You get a Date object
Set the timezone of the SimpleDateFormat to "UTC" (or use a different SimpleDateFormat instance)
Format the date (if you want the result as a string as well)
Example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class ConvertToUTC {
public static void main(String[] args) throws Exception {
String dateval = "2016-12-21T07:48:36";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT+14"));
Date date = df.parse(dateval);
System.out.println(df.format(date)); // GMT+14
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(date)); // UTC
}
}
use "GMT+14:00" instead of "UTC+14:00"
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("GMT+14:00"));
final Date d = f.parse("2016-12-21T07:48:36");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(d)); // -> 2016-12-20T05:48:36
tl;dr
LocalDateTime.parse( "2016-12-21T07:48:36" ) // Parse as a `LocalDateTime` given the lack of an offset or zone. *Not* an actual moment, only a rough approximation of potential moments along a range of about 26-27 hours.
.atOffset( ZoneOffset.ofHours( 14 ) ) // Assign an offset-from-UTC as context, giving meaning to determine an actual point on the timeline.
.toInstant() // Renders `Instant` object in UTC.
java.time
The modern way is with the java.time classes built into Java 8 and later. Much of the functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project.
ZoneOffset offset = ZoneOffset.ofHours( 14 ); // fourteen hours ahead of UTC.
Parse the string as a LocalDateTime as it lacks any info about offset or zone. Your input is in standard ISO 8601 format, so no need to specify a formatting pattern.
LocalDateTime ldt = LocalDateTime.parse( "2016-12-21T07:48:36" );
Apply the offset to the local date-time to get an OffsetDateTime an object.
OffsetDateTime odt = ldt.atOffset( offset );
From that, extract an Instant which is always in UTC.
Instant instant = odt.toInstant();
instant.toString(): 2016-12-20T17:48:36Z
In UTC, the value is a different date, the 20th instead of 21st.
See live code at IdeOne.com.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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, 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.

Convert Japan's date format (2013年11月24日) to normal date format (2013-11-24)

I have a date picker field on my JSP page. While selecting that field, the date is displayed in Japanese format (2013年11月24日) in my text field. Now, while reading that date field in my controller, I am getting this value 2013年11月24日.
How can I convert this date format into normal date format?
It seems the format you've given is the default date format of the Japanese locale, so you can use the build in facility:
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, new Locale("ja"));
Javadoc: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
IDEONE example: http://ideone.com/0W7szq
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, new Locale("ja"));
System.out.println(df.format(new Date()));
System.out.println(df.parse("2013年11月24日"));
Output:
2013年11月24日
Sun Nov 24 00:00:00 GMT 2013
Edit:
Please note that this DateFormat class is not thread-safe, so you cannot make the instant static. If you do not want to create the instance again and again like above, you may want to look into the thread-safe variant in Joda time: DateTimeFormat.
The Answer by billc.cn is correct but outdated. The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
java.time
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL );
f = f.withLocale( Locale.forLanguageTag("ja") ) ;
String input = "2013年11月24日" ;
LocalDate ld = LocalDate.parse( input , f );
input: 2013年11月24日
ld.toString(): 2013-11-24
See live code in IdeOne.com.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You should be using LocalDate objects to hold your date-only values in your business logic and data model. Generate the strings only as needed for presentation such as display in your JSP page.
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.
Are the delimiters always the same?
If so, can't you just use SimpleDateFormat("yyyy年MM月dd")?

Java date is not preserving milliseconds in conversion with simple date format

I'm trying to convert the following string "2012-04-13 04:08:42.794" to a date type:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date convertedDate;
try {
convertedDate = dateFormat.parse(dateString);
System.out.println(" in utils: "+convertedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
//----------------- i think this is the problem
java.sql.Date sqlDate = new java.sql.Date(convertedDate.getTime());
System.out.println("sql: "+sqlDate.toString());
return sqlDate;
But this is printing the following:
in utils: Fri Apr 13 04:08:42 PDT 2012
How can I get this date to preserve the milliseconds?
The convertedDate object does in fact contain the millisecond information. The issue here is that the toString() method format does not print milliseconds.
Do
System.out.println(" in utils: " + dateFormat.format(convertedDate));
You can also check if the ms are set with
System.out.println("millis: " + convertedDate.getTime());
He's my go at it (trying to keep the same code style as yours) :
import java.util.*;
import java.text.*;
public class main {
public static void main(String[] args)throws Exception {
long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss.SSS");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate)); }
}
Output :
Jan 13,1970 17:53:13.190
Regards, Erwald
Instead of printing using toString() you can make your own printing method, so it prints the information you want specifically. Also note that most of the Date class is deprecated - look at http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Calendar now = Calendar.getInstance();
System.out.println("Current milliseconds since Jan 1, 1970 are :"
+ now.getTimeInMillis());
just use java.util.Calendar http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
tl;dr
myPreparedStatetment.setObject(
… ,
LocalDateTime.parse(
"2012-04-13 04:08:42.794".replace( " " , "T" )
)
)
Details
The Answer by SJuan76 is correct: You are being fooled by the poorly-designed output of the Date::toString method. Instead, use java.time classes.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes such as Date/Calendar.
First convert your input string to fully comply with the ISO 8601 standard. Replace the SPACE in the middle with a T.
String input = "2012-04-13 04:08:42.794".replace( " " , "T" ) ;
Parse as a LocalDateTime since your input lacks an indicator of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2012-04-13T04:08:42.794
SQL
Avoid the date-time related java.sql classes. They too are supplanted by the java.time classes. As of JDBC 4.2, you can directly exchange java.time objects with your database. So you can forget all about the java.sql.Date class and its terrible hacked design.
myPreparedStatement.setObject( … , ldt ) ;
And…
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
Morals
Moral of the story # 1: Use smart objects, not dumb strings.
Moral of the story # 2: Use only java.time objects. Avoid legacy date-time classes.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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, 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.

Validate range with java Date and SimpleDateFormat [duplicate]

This question already has answers here:
Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)
(4 answers)
Closed 4 years ago.
Is there a Date exception that I can deal with when I try to parse a date with this code here:
try{
SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy");
Date date = df.parse(dateRelease);
}catch (ParseException e) {}
Well, if the "dateRelease" isn't in a correct format type it throws ParseException, but I want to get if someone write like "40/03/2010" - WRONG with day, month or year invalid range. Actually, when a invalid date is sent, SimpleDateFormat just create a new Date with default numbers.
Do I have to create my own method with a regex to deal with it or is there an existing exception that tells me it to catch?
Make it non-lenient by SimpleDateFormat#setLenient() with a value of false.
SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy");
df.setLenient(false);
Date date = df.parse(dateRelease);
Then it will throw ParseException when the date is not in a valid range.
tl;dr
try {
LocalDate localDate = LocalDate.parse(
"40:03:2010" , // "40:03:2010" is bad input, "27:03:2010" is good input.
DateTimeFormatter.ofPattern( "dd:MM:uuuu" )
) ;
} catch ( DateTimeParseException e ) {
… // Invalid input detected.
}
Using java.time
The modern way is with the java.time classes built into Java 8 and later.
Your example data does not match the format shown in your example code. One uses SOLIDUS (slash) character, the other uses COLON character. I'll go with COLON.
DateTimeFormatter
Define a formatting pattern to match the input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd:MM:uuuu" );
LocalDate
Parse as a LocalDate object as the input has no time-of-day and no time zone.
LocalDate localDateGood = LocalDate.parse( "27:03:2010" , f );
System.out.println( "localDateGood: " + localDateGood );
Now try some bad input. Trap for the appropriate exception.
try {
LocalDate localDateBad = LocalDate.parse( "40:03:2010" , f );
} catch ( DateTimeParseException e ) {
System.out.println( "ERROR - Bad input." );
}
See this code run live in IdeOne.com.
localDateGood: 2010-03-27
ERROR - Bad input.
ISO 8601
Use standard ISO 8601 formats when exchanging/storing date-time values as text. The standard formats are sensible, practical, easily read by humans of various cultures, and easy for machines to parse.
For a date-only value the standard format is YYYY-MM-DD such as 2010-03-27.
The java.time classes use standard ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern at all.
LocalDate localDate = LocalDate.parse( "2010-03-27" );
String output = localDate.toString(); // 2010-03-27
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 moment in ISO 8601 format with date, hour, and minute?

What is the most elegant way to get ISO 8601 formatted presentation of the current moment, UTC? It should look like: 2010-10-12T08:50Z.
Example:
String d = DateFormat.getDateTimeInstance(DateFormat.ISO_8601).format(date);
Use SimpleDateFormat to format any Date object you want:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Using a new Date() as shown above will format the current time.
Java 8 Native
java.time makes it simple since Java 8. And thread safe.
ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT )
Result: 2015-04-14T11:07:36.639Z
You may be tempted to use lighter Temporal such as Instant or LocalDateTime,
but they lacks formatter support or time zone data.
Only ZonedDateTime works out of the box.
By tuning or chaining the options / operations of ZonedDateTime and DateTimeFormatter, you can easily control the timezone and precision, to a certain degree:
ZonedDateTime.now( ZoneId.of( "Europe/Paris" ) )
.truncatedTo( ChronoUnit.MINUTES )
.format( DateTimeFormatter.ISO_DATE_TIME )
Result: 2015-04-14T11:07:00+01:00[Europe/Paris]
Refined requirements, such as removing the seconds part, must still be served by custom formats or custom post process.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // 2015-04-14T11:07:00
.format( DateTimeFormatter.ISO_LOCAL_DATE ) // 2015-04-14
.format( DateTimeFormatter.ISO_LOCAL_TIME ) // 11:07:00
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm" ) ) // 2015-04-14 11:07
For Java 6 & 7, you may consider back-ports of java.time such as ThreeTen-Backport, which also has an Android port.
Both are lighter than Joda, and has learned from Joda's experience - esp. considering that java.time is designed by Joda's author.
For systems where the default Time Zone is not UTC:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
The SimpleDateFormat instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.
EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone does not accept a String (corrected by Paul)
As of Java 8 you can simply do:
Instant.now().toString();
From the java.time.Instant docs:
now
public static Instant now()
Obtains the current instant from the system clock.
This will query the system UTC clock to obtain the current instant.
toString
public String toString()
A string representation of this instant using ISO-8601 representation.
The format used is the same as DateTimeFormatter.ISO_INSTANT.
Java 8:
thisMoment = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX")
.withZone(ZoneOffset.UTC)
.format(Instant.now());
Pre Java 8:
thisMoment = String.format("%tFT%<tRZ",
Calendar.getInstance(TimeZone.getTimeZone("Z")));
From the docs:
'R' Time formatted for the 24-hour clock as "%tH:%tM"
'F' ISO 8601 complete date formatted as "%tY-%tm-%td".
use JodaTime
The ISO 8601 calendar system is the default implementation within Joda-Time
Here is the doc for JodaTime Formatter
Edit:
If you don't want to add or if you don't see value of adding above library you could just use in built SimpleDateFormat class to format the Date to required ISO format
as suggested by #Joachim Sauer
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());
DateFormatUtils from Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT
If you don't want to include Jodatime (as nice as it is)
javax.xml.bind.DatatypeConverter.printDateTime(
Calendar.getInstance(TimeZone.getTimeZone("UTC"))
);
which returns a string of:
2012-07-10T16:02:48.440Z
which is slightly different to the original request but is still ISO-8601.
ISO 8601 may contains seconds
see http://en.wikipedia.org/wiki/ISO_8601#Times
so the code should be
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
tl;dr
Some of the other Answers are correct in recommending java.time classes but go about using unnecessary lengths for your specific needs.
Instant.now() // Capture the current moment in UTC with a resolution as fines nanoseconds but usually in microseconds or milliseconds.
.truncatedTo( ChronoUnit.MINUTES ) // Lop off any seconds or fractional second, to get a value in whole minutes.
.toString() // Generate a String in standard ISO 8601 format where a `T` separates the year-month-day from the hour-minute-second, and the `Z` on the end for “Zulu” means UTC.
2018-01-23T12:34Z
Instant::toString
The jav.time.Instant class represents a moment in UTC, always in UTC.
Instant instant = Instant.now() ;
instant.toString(): 2018-01-23T12:34:56.123456Z
The Z on the end of your example string 2010-10-12T08:50Z is pronounced “Zulu” and means UTC.
Your desired format happens to comply with the ISO 8601 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern. Just call Instant::toString as seen above.
If you specifically want whole minutes without second or fractional second, then truncate. Specify a unit of time via ChronoUnit class.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
String output = instant.toString(); // Generate a `String` object in standard ISO 8601 format.
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, 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.
Joda-Time
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. For Java 6 & 7, see the ThreeTen-Backport project, further adapted for Android in the ThreeTenABP project.
Using the Joda-Time library…
String output = new DateTime( DateTimeZone.UTC ).toString() ;
This is thread-safe. Joda-Time creates new immutable objects rather than changing existing objects.
If you truly intended to ask for a format without seconds, resolving to minutes, then use one of the many other built-in formatters in Joda-Time.
DateTime now = new DateTime( DateTimeZone.UTC ) ;
String output = ISODateTimeFormat.dateHourMinute.print( now ) ;
java.time
For Java 8 and later, Joda-Time continues to work. But the built-in java.time framework supplants Joda-Time. So migrate your code from Joda-Time to java.time as soon as is convenient.
See my other Answer for a modern solution.
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, 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.
For Java version 7
You can follow Oracle documentation:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
X - is used for ISO 8601 time zone
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
System.out.println(nowAsISO);
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
//nowAsISO = "2013-05-31T00:00:00Z";
Date finalResult = df1.parse(nowAsISO);
System.out.println(finalResult);
I do believe the easiest way is to first go to instant and then to string like:
String d = new Date().toInstant().toString();
Which will result in:
2017-09-08T12:56:45.331Z
You could use Java's SimpleDateFormat with the following pattern yyyy-MM-dd'T'HH:mm:ssXXX for ISO 8601.
Sample Code: (lists out for all the available time zones)
for (String timeZone : TimeZone.getAvailableIDs())
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
String formatted = dateFormat.format(new Date());
System.out.print(formatted);
if (formatted.endsWith("Z"))
{
// These time zone's have offset of '0' from GMT.
System.out.print("\t(" + timeZone + ")");
}
System.out.println();
}
You could use:
TimeZone.getDefault()
for the default vm timezone. More here
You might notice the date time for few time zones that end with 'Z'. These time zones have offset of '0' from GMT.
More info can be found here.
private static String getCurrentDateIso()
{
// Returns the current date with the same format as Javascript's new Date().toJSON(), ISO 8601
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.format(new Date());
}
Here's a whole class optimized so that invoking "now()" doesn't do anything more that it has to do.
public class Iso8601Util
{
private static TimeZone tz = TimeZone.getTimeZone("UTC");
private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
static
{
df.setTimeZone(tz);
}
public static String now()
{
return df.format(new Date());
}
}
DateTimeFormatter.ISO_DATE_TIME
.withZone(ZoneOffset.UTC)
.format(yourDateObject.toInstant())
Still, joda-time does only support the extended format:
"2015-12-09T00:22:42.930Z"
not the basic:
"20151209T002242.930Z"
...we might be better off testing a list of formats with java SimpleDateFormat.
I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.
private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";
public static Calendar isoToCalendar(final String inputDate) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
Date date = dateFormat.parse(inputDate);
calendar.setTime(date);
} catch (ParseException e) {
Log.e("TAG",e.getMessage());
}
return calendar;
}
REMEMBER:
The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.
If you care about performance, I created a library which outperforms standard Java parser and formatter in manipulating with ISO8601-formatted dates. DatetimeProcessor implementations are thread-safe and can be cached in a concurrent map or static fields.
<dependency>
<groupId>com.axibase</groupId>
<artifactId>date-processor</artifactId>
<version>1.0.3</version>
</dependency>
import com.axibase.date.DatetimeProcessor;
import com.axibase.date.PatternResolver;
import org.junit.Before;
import org.junit.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class DateFormatTest {
private Clock clock;
#Before
public void prepare() {
clock = Clock.fixed(Instant.ofEpochMilli(1571285405300L), ZoneId.of("Europe/Berlin"));
}
#Test
public void testIsoMillis(){
final DatetimeProcessor formatter = PatternResolver.createNewFormatter("iso");
assertThat(formatter.print(clock.millis(), ZoneOffset.UTC), is("2019-10-17T04:10:05.300Z"));
}
#Test
public void testIsoMillisLocalZone(){
final DatetimeProcessor formatter = PatternResolver.createNewFormatter("iso");
assertThat(formatter.print(clock.millis(), clock.getZone()), is("2019-10-17T06:10:05.300+02:00"));
}
#Test
public void testIsoMinutes(){
final DatetimeProcessor formatter = PatternResolver.createNewFormatter("yyyy-MM-ddTHH:mmXXX");
assertThat(formatter.print(clock.millis(), ZoneOffset.UTC), is("2019-10-17T04:10Z"));
}
}
They should have added some kind of simple way to go from Date to Instant and also a method called toISO8601, which is what a lot of people are looking for.
As a complement to other answers, from a java.util.Date to ISO 8601 format:
Instant.ofEpochMilli(date.getTime()).toString();
It is not really visible when using auto-completion but:
java.time.Instant.toString():
A string representation of this instant using ISO-8601
For those using Joda Time, here's a one-liner in the format yyyy-MM-dd'T'HH:mm:ss'Z'
DateTime(timeInMillis, DateTimeZone.UTC).toString(ISODateTimeFormat.dateTimeNoMillis())
Try This,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
String date=sdf.format (new Date() );
Its For ISO 8601 format

Categories