I have the timestamp in form of 03-AUG-12 08.15.00.000000000 PM -05:00
I am unable to get a String representation in form on yyyy-MM-dd HH:mm:ss.
Here is my code :
public static void convert() {
String oldstring = "03-AUG-12 08.15.00.000000000 PM -05:00";
Date date = null;
try {
date = new SimpleDateFormat("dd-MMM-yy HH.mm.ss.S aa").parse(oldstring);
}
catch (ParseException e) {
e.printStackTrace();
}
String newstring = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(newstring);
}
Basically it is a timestamp with timezone format from the Oracle database.
You can't use SimpleDateFormat to parse such a string, at least not without some limitations:
A time zone designator like -05:00 (according to ISO 8601) is not supported until Java 7. With Java 7 you can use the XXX pattern to parse it.
To parse the month name correctly, you should specify that you require an English locale.
The pattern for milliseconds (S) parses an unlimited number of digits. If your string contains "08.15.00.100000000", SimpleDateFormat would parse this as 8:15:00 and 100000000ms, adding almost 28 hours to the expected value. If you are sure that the value is always 0, you can ignore this problem.
If you can accept the last issue and use Java 7, you should be using something like this:
new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa XXX", Locale.ENGLISH)
Change this line like this:
date = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa").parse(oldstring);
You need to use the lowercase h which parses the AM/PM hours 1-12.
tl;dr
DateTimeFormatter f = new DateTimeFormatterBuilder ().parseCaseInsensitive ().appendPattern ( "dd-MMM-yy hh.mm.ss.SSSSSSSSS a ZZZZZ" ).toFormatter ().withLocale ( Locale.US );
OffsetDateTime odt = OffsetDateTime.parse ( "03-AUG-12 08.15.00.000000000 PM -05:00" , f );
Objects, not strings
You mentioned Oracle. When retrieving data from a database, use objects rather than strings. Ask your ResultSet for a java.sql.Timestamp object.
java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Convert from the troublesome old date-time class to the modern java.time type. Look to new methods added on the old classes to facilitate conversion to/from java.time.
Instant instant = ts.toInstant();
Or preferably, if using JDBC 4.2 or later, and using Java 8 or later, you may be able to retrieve an java.time.Instant via the ResultSet::getObject method.
But if you must parse a string, read on.
Avoid old date-time classes
The old date-time classes bundled with the earliest versions of Java are troublesome and confusing. Now supplanted by the java.time classes.
Nanoseconds
That bunch of zeros must represent a fraction of a second with nanosecond resolution, up to nine digits of a decimal fraction. The old date-time classes can handle only milliseconds, but fortunately the modern java.time classes can indeed handle a resolution up to nanoseconds.
Using java.time
Define a formatting pattern to parse the given input. By the way, your data’s format is less than optimal; in the future, use ISO 8601 standard formats for strings that represent date-time values.
We use a “builder” in order to specify case-insensitive parsing. Proper abbreviation for a name of month in English is initial-cap, Aug, but your input uses all-caps.
String pattern = "dd-MMM-yy hh.mm.ss.SSSSSSSSS a ZZZZZ";
DateTimeFormatterBuilder fb = new DateTimeFormatterBuilder ().parseCaseInsensitive ().appendPattern ( pattern );
Tell the builder to instantiate our formatter. The Locale to determines (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Locale l = Locale.US;
DateTimeFormatter f = fb.toFormatter ().withLocale ( l );
Finally, parse the string as an OffsetDateTime object.
String input = "03-AUG-12 08.15.00.000000000 PM -05:00";
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
Dump to console. Note how our 8 PM is transformed into the 24-hour clock value of 20 hours.
System.out.println ( "input: " + input + " | odt.toString(): " + odt );
input: 03-AUG-12 08.15.00.000000000 PM -05:00 | odt.toString(): 2012-08-03T20:15-05:00
A time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST). If desired, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( “America/Montreal” );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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
I am exporting data into a file in a Java application using NetBeans. The file will have a hard coded name given by me in the code. Please find below the code.
private static String FILE = "D:\\Report.pdf";
I want to append date and time stamp to the file name generated so that each file created is a unique file. How to achieve this?
tl;dr
"Report" + "_"
+ Instant.now() // Capture the current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off the fractional second, as superfluous to our purpose.
.toString() // Generate a `String` with text representing the value of the moment in our `Instant` using standard ISO 8601 format: 2016-10-02T19:04:16Z
.replace( "-" , "" ) // Shorten the text to the “Basic” version of the ISO 8601 standard format that minimizes the use of delimiters. First we drop the hyphens from the date portion
.replace( ":" , "" ) // Returns 20161002T190416Z afte we drop the colons from the time portion.
+ ".pdf"
Report_20161002T190416Z.pdf
Or define a formatter for this purpose. The single-quote marks ' mean “ignore this chunk of text; expect the text, but do not interpret”.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "'Report_'uuuuMMdd'T'HHmmss'.pdf'" ) ;
String fileName = OffsetDateTime.now( ZoneOffset.UTC ).truncatedTo( ChronoUnit.SECONDS ).format( f ) ;
Use same formatter to parse back to a date-time value.
OffsetDateTime odt = OffsetDateTime.parse( "Report_20161002T190416Z.pdf" , f ) ;
java.time
The other Answers are correct but outdated. The troublesome old legacy date-time classes are now supplanted by the java.time classes.
Get the current moment 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.now(); // 2016-10-02T19:04:16.123456789Z
Truncate fractional second
You probably want to remove the fractional second.
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS );
Or if you for simplicity you may want to truncate to whole minutes if not rapidly creating such files.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES );
You can generate a string in standard ISO 8601 format by calling toString.
String output = instant.toString();
2016-10-02T19:04:16Z
Stick with UTC
The Z on the end is short for Zulu and means UTC. As a programmer always, and as a user sometimes, you should think of UTC as the “One True Time” rather than “just another time zone”. You can prevent many problems and errors by sticking with UTC rather than any particular time zone.
Colons
Those colons are not allowed in the HFS Plus file system used by Mac OS X (macOS), iOS, watchOS, tvOS, and others including support in Darwin, Linux, Microsoft Windows.
Use ISO 8601 standard formats
The ISO 8601 standard provides for “basic” versions with a minimal number of separators along with the more commonly used “extended” format seen above. You can morph that string above to the “basic” version by simply deleting the hyphens and the colons.
String basic = instant.toString().replace( "-" , "" ).replace( ":" , "" );
20161002T190416Z
Insert that string into your file name as directed in the other Answers.
More elegant
If you find the calls to String::replace clunky, you can use a more elegant approach with more java.time classes.
The Instant class is a basic building-block class, not meant for fancy formatting. For that, we need the OffsetDateTime class.
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS );
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
Now define and cache a DateTimeFormatter for the “basic” ISO 8601 format.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" );
Use that formatter instance to generate a String. No more needing to replace characters in the String.
String output = odt.format( formatter );
You can also use this formatter to parse such strings.
OffsetDateTime odt = OffsetDateTime.parse( "20161002T190416Z" , formatter );
Zoned
If you decide to use a particular region’s wall-clock time rather than UTC, apply a time zone in a ZoneId to get a ZonedDateTime object. Similar to an OffsetDateTime but a time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Use the same formatter as above, or customize to your liking.
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.
Use SimpleDateFormat and split to keep file extension:
private static String FILE = "D:\Report.pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE.split(".")[0] + df.format(new Date()) + FILE.split(".")[1];
// filename = "D:\Report20150915152301.pdf"
UPDATE: if you are able to modify FILE variable, my suggestion will be:
private static String FILE_PATH = "D:\Report";
private static String FILE_EXTENSION = ".pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE_PATH + df.format(new Date()) + "." + FILE_EXTENSION;
// filename = "D:\Report20150915152301.pdf"
You can do something like that
Define your file name pattern as below :
private static final String FILE = "D:\Report_{0}.pdf";
private static final String DATE_PATTERN = "yyyy-MM-dd:HH:mm:ss";
The {0} is a marker to be replaced by the following code
private String formatFileName(Date timeStamp) {
DateFormat dateFormatter = new SimpleDateFormat(DATE_PATTERN);
String dateStr = dateFormatter.format(timeStamp);
return MessageFormat.format(FILE, dateStr);
}
For further information over date format you can see there and MessageFormat there
Below is my code for formatting time
public class FormatTime {
public static void main(String[] args) throws Exception {
FormatTime ft = new FormatTime();
System.out.println(ft.evaluate("12/01/2014 05:30:15 PM","MM/dd/yyyy hh:mm:ss aa", "yyyy-MM-dd HH:mm:ss"));
}
public String evaluate(String time,String iFormat ,String f) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(f);
SimpleDateFormat inFormat = new SimpleDateFormat(iFormat);
Date date=inFormat.parse(time);
String fechaNueva = format.format(date);
return fechaNueva;
}
}
Out put of this program is as expected that it give 2014-12-01 17:30:15.
But when I replace hh to HH in iFormat (same as in outputformat) then it give output in 12 out format 2014-12-01 05:30:15
Same also happens if I convert both in lower case that is hh. Why does this type of inconsistency occur?
I don't think it's inconsistent. When you evaluate the time using HH it will ignore the aa bit, as it's evaluating the input as a 24-hour time, and the aa bit makes no sense. However, when you run it with hh it will read 05:30:15 PM as "half five in the afternoon" and writing it will give 2014-12-01 17:30:15. Reading 05:30:15 PM as a 24-hour time, will read it as "half five in the morning", throwing the PM bit away.
When having both formats with hh, you're both reading and writing in 12 hour format. For at to make sense, you would need to add the aa bit to the output format as well.
I hope that answers your question in a way that makes sense :)
tl;dr
LocalDateTime.parse( // Parse as a date-time lacking time zone or offset-from-UTC.
"12/01/2014 05:30:15 PM" , // Define a formatting pattern to match input. Case-sensitive formatting code. Use `h` lowercase for 12-hour clock, 0-12. Use uppercase `H` for 24-hour clock, 0-23.
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US )
).format( // Generate a String in specific format. Generally better to let java.time localize automatically.
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US )
)
java.time
The modern approach uses java.time classes that supplanted the troublesome old date-time classes.
Get the current moment in UTC. 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() ;
To see that same moment through the lens of a wall-clock time used by people of a certain region (time zone), apply a ZoneId to get a ZonedDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate a string in standard ISO 8601 format on any of these, call toString. The java.time classes use standard formats by default when paring/generating strings. So no need to specify a formatting pattern.
If you want other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes. You can specify a formatting pattern, but easier to let java.time automatically localize.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
mercredi 14 février 2018 à 00:59:07 heure normale d’Europe centrale
Or, Locale.US & FormatStyle.SHORT.
2/14/18, 1:01 AM
Your custom format for your input is:
String input = "12/01/2014 05:30:15 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" , Locale.US ) ;
That input string lacks any indicator of a time zone or offset-from-UTC. So it is not a moment, not a specific point on the timeline. It represents a vague idea about potential moments along a range of about 26-27 hours. As such, we parse this input into a LocalDateTime lacking any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2014-12-01T17:30:15
Generate a string in that format.
String output = ldt.format( f ) ;
12/01/2014 05:30:15 PM
As others explained, the formatting codes are case-sensitive. If you want 24-hour time, use uppercase H. For 12-hour time, use lowercase h.
Note that the formatting codes in java.time are close to those of the legacy SimpleDateFormat but not exactly the same. Study the documentation and search Stack Overflow for many examples.
When exchanging date-time values as text, stick with the standard ISO 8601 formats.
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.
I have formatted date in the form of string and i want it in date format without changing formatted pattern
here is my code
Date currDate = new Date();//Fri Oct 31 03:48:24 PDT 2014
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
String formattedDate= formatter.format(currDate);//2014-10-31 04:23:42
here am getting in "yyyy-MM-dd hh:mm:ss" format and the same format i want it in date.
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date paidDate = sdf.parse(formattedDate);
System.out.println(pattern + " " + paidDate);//Fri Oct 31 03:48:24 PDT 2014
but i am getting result as Fri Oct 31 03:48:24 PDT 2014, so pls help me to get result as 2014-10-31 04:23:42 in date format
If I understood your problem correctly:
System.out.println(pattern + " " + sdf.format(paidDate);
You seem to be under the mistaken impression that a Date object somehow encodes format of the original date. It doesn't.
So ... when you do this:
Date paidDate = sdf.parse(formattedDate);
it does not "remember" original format of the text form of the date in paidDate. And it cannot. If you want to print / unparse a Date in any format than the default one, you should use a DateFormat and call its format method. Calling toString() will just give you the date in the default format.
Try this.
System.out.println(formatter.format(paidDate));
tl;dr
Do not conflate a date-time object with a string representing its value. A date-time object has no “format”.
ZonedDateTime.now( // Instantiate a `ZonedDateTime` object capturing the current moment.
ZoneId.of( "Africa/Tunis" ) // Assign this time zone through which we see the wall-clock time used by the people of this particular region.
).format( // Generate a string representing the value of this `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) // Define a formatting pattern to match your desire.
)
2018-03-10 07:36:23
Calling ZonedDateTime::toString generates a string in standard ISO 8601 format.
2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
Date-time object has no “format”
You are confusing a date-time object in Java, or a date-time value stored in a database, with a textual representation. You can generate a string from a date-time object (or database value), but that string is separate and distinct from the value it represents. Do not conflate a string with its generating creator.
java.time
Avoid using the troublesome old date-time classes such as Date, Calendar, and SimpleDateFormat. Instead, use Instant, ZonedDateTime, and DateTimeFormatter classes, respectively.
If you have an input string such as 2014-10-31 04:23:42, replace the SPACE in the middle with a T to comply with ISO 8601 standard format. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
String input = "2014-10-31 04:23:42".replace( " " , "T" ) ;
That input lacks any indicator of time zone or offset-from-UTC. So parse as a LocalDateTime which purposely lacks any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2014-10-31T04:23:42
A LocalDateTime does not represent a moment, is not a point on the timeline. To determine an actual moment, you must supply the context of a zone or offset.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Now we have an actual moment, a point on the timeline.
To capture the current moment in UTC, use Instant.
Instant instant = Instant.now() ;
Adjust into another zone.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
I do not recommend generating strings lacking an indicator of zone/offset. But if you insist, use the built-in DateTimeFormatter and then replace the T in the middle with a SPACE to get your desired format.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2018-03-10 07:36:23.595362
If you really do not want the fractional second, then define your own formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;
2018-03-10 07:36:23
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.
How should I correctly format Date and Time Strings for the Android platform?
Here is some code:
String path = getFilesDir().getPath();
String filePath = path + "/somefile.xml";
File file = new File(filePath);
Date lastModDate = new Date(file.lastModified());
String filelastModDate = "Updated: " + lastModDate.toString();
You can format it various way...
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String currentTime = sdf.format(date);
Here you can put other format like
k:mm
h:mm
h:mm dd/MM/yyyy
etc.....
check this.... http://developer.android.com/reference/java/text/SimpleDateFormat.html
Thanks #receme I solved it. like this:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a",Locale.getDefault());
String currentTime = sdf.format(date);
Log.i(LOGTAG,"Current Time: " + currentTime);
tl;dr
Instant.ofEpochMilli( // Parse milliseconds count to a moment in UTC.
file.lastModified() // A count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object.
.format( // Generate a `String`.
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL ) // Specify how long or abbreviated.
.withLocale( Locale.JAPAN ) // Specify a `Local` to determine human language and cultural norms used in localizing.
) // Returns a `String`.
java.time
The modern approach uses the java.time classes.
The File.lastModified method returns a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
long millisSinceEpoch = file.lastModified() ;
Parse that number as a modern java.time object.
Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;
Generate a String to represent that values using standard ISO 8601 format.
String output = instant.toString() ; // Generate a `String` in standard ISO 8601 format.
2018-07-16T22:40:39.937Z
To view the same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
2018-07-17T10:40:39.937+12:00[Pacific/Auckland]
Let java.time automatically localize. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
mardi 17 juillet 2018 à 10:40:39 heure normale de la Nouvelle-Zélande
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.
I would like to add my share here.
Note that the user can set his preferred format in the settings. Example on how to retrieve:
static DateFormat getUserDateFormat(Context context) {
if (mUserDateFormat == null)
mUserDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
return mUserDateFormat;
}
See also ...getTimeFormat
You then have a java DateFormat to use with above mentioned examples.
Furthermore, Android contains it's own TextFormat class, look here: http://developer.android.com/reference/android/text/format/package-summary.html
This may look like:
static String getAppExpiredString() {
String date = android.text.format.DateFormat.getDateFormat(getAppContext()).format(App_Main.APP_RUN_TILL.getTime());
return getAppContext().getString(R.string.app_expired) + " " + date + ".";
}
Update: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Joda-Time
Install third-party library, Joda-Time.
By default, Joda-Time outputs strings in ISO 8601 format. That format is intuitively understandable by virtually anybody worldwide.
Search StackOverflow.com for many more examples.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
DateTime now = new DateTime();
System.out.println( now );
When run…
2013-12-05T19:55:43.897-08:00
Though, The question is very old, but it may help one who wants it Kotlin version of this answer. Here I take a empty file name DateUtil and create a function called getDateString() which has 3 arguments.
1st argument : Your input date
2nd argument : Your input date pattern
3rd argument : Your wanted date pattern
DateUtil.kt
object DatePattern {
const val YEAR_MONTH_DAY = "yyyy-MM-dd"
const val DAY_MONTH_YEAR = "dd-MM-yyyy"
const val RFC3339 = "yyyy-MM-dd'T'HH:mm:ss'Z'"
}
fun getDateString(date: String, inputDatePattern: String, outputDatePattern: String): String {
return try {
val inputFormat = SimpleDateFormat(inputDatePattern, getDefault())
val outputFormat = SimpleDateFormat(outputDatePattern, getDefault())
outputFormat.format(inputFormat.parse(date))
} catch (e: Exception) {
""
}
}
And now use this method in your activity/fuction/dataSourse Mapper to get Date in String format like this
getDate("2022-01-18T14:41:52Z", RFC3339, DAY_MONTH_YEAR)
and output will be like this
18-01-2022
I have a String of a date and time like this: 2011-04-15T20:08:18Z. I don't know much about date/time formats, but I think, and correct me if I'm wrong, that's its UTC format.
My question: what's the easiest way to parse this to a more normal format, in Java?
tl;dr
String output =
Instant.parse ( "2011-04-15T20:08:18Z" )
.atZone ( ZoneId.of ( "America/Montreal" ) )
.format (
DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL )
.withLocale ( Locale.CANADA_FRENCH )
)
;
vendredi 15 avril 2011 16 h 08 EDT
Details
The answer by Josh Pinter is correct, but could be even simpler.
java.time
In Java 8 and later, the bundled java.util.Date/Calendar classes are supplanted by the java.time framework defined by JSR 310. Those classes are inspired by Joda-Time but are entirely re-architected.
The java.time framework is the official successor to Joda-Time. The creators of Joda-Time have advised we should migrate to java.time as soon as is convenient. Joda-Time continues to be updated and tweaked, but further innovation will be done only in java.time and its extensions in the ThreeTen-Extra project.
The bulk of java.time functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in ThreeTenABP project.
The equivalent for the Joda-Time code above is quite similar. Concepts are similar. And like Joda-Time, the java.time classes by default use ISO 8601 formats when parsing/generating textual representations of date-time values.
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds (versus milliseconds used by Joda-Time & java.util.Date).
Instant instant = Instant.parse( "2011-04-15T20:08:18Z" );
Apply a time zone (ZoneId) to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Adjust into yet another time zone.
ZoneId zoneId_NewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt.withZoneSameInstant( zoneId_NewYork );
To create strings in other formats beyond those of the toString methods, use the java.time.format classes. You can specify your own formatting pattern or let java.time localize automatically. Specify a Locale for (a) the human language used in translation of name of month/day-of-week, and (b) cultural norms for period-versus-comma, order of the parts, and such.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL );
formatter = formatter.withLocale( Locale.US );
String output = zdt_NewYork.format( formatter );
Friday, April 15, 2011 4:08:18 PM EDT
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. This section left intact for history.
Pass String To Constructor
Joda-Time can take that string directly. Simply pass to a constructor on the DateTime class.
Joda-Time understands the standard ISO 8601 format of date-times, and uses that format as its default.
Example Code
Here is example code in Joda-Time 2.3 running in Java 7 on a Mac.
I show how to pass the string to a DateTime constructor, in two ways: With and without a time zone. Specifying a time zone solves many problems people encounter in doing date-time work. If left unspecified, you get the default time zone which can bring surprises when placed into production.
I also show how specify no time zone offset (UTC/GMT) using the built-in constant DateTimeZone.UTC. That's what the Z on the end, short for Zulu time, means: No time zone offset (00:00).
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Default time zone.
DateTime dateTime = new DateTime( "2011-04-15T20:08:18Z" );
// Specified time zone.
DateTime dateTimeInKolkata = new DateTime( "2011-04-15T20:08:18Z", DateTimeZone.forID( "Asia/Kolkata" ) );
DateTime dateTimeInNewYork = new DateTime( "2011-04-15T20:08:18Z", DateTimeZone.forID( "America/New_York" ) );
// In UTC/GMT (no time zone offset).
DateTime dateTimeUtc = dateTimeInKolkata.toDateTime( DateTimeZone.UTC );
// Output in localized format.
DateTimeFormatter formatter = DateTimeFormat.shortDateTime().withLocale( Locale.US );
String output_US = formatter.print( dateTimeInNewYork );
Dump to console…
System.out.println("dateTime: " + dateTime );
System.out.println("dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println("dateTimeInNewYork: " + dateTimeInNewYork );
System.out.println("dateTimeUtc: " + dateTimeUtc );
System.out.println("dateTime in US format: " + output_US );
When run…
dateTime: 2011-04-15T13:08:18.000-07:00
dateTimeInKolkata: 2011-04-16T01:38:18.000+05:30
dateTimeInNewYork: 2011-04-15T16:08:18.000-04:00
dateTimeUtc: 2011-04-15T20:08:18.000Z
dateTime in US format: 4/15/11 4:08 PM
Use JodaTime
I kept getting parsing errors using the other solutions with the Z at the end of the format.
Instead, I opted to leverage JodaTime's excellent parsing functionality and was able to do the following very easily:
String timestamp = "2011-04-15T20:08:18Z";
DateTime dateTime = ISODateTimeFormat.dateTimeParser().parseDateTime(timestamp);
This correctly recognizes the UTC timezone and allows you to then use JodaTime's extensive manipulation methods to get what you want out of it.
Hope this helps others.
Already has lot of answer but just wanted to update with java 8 in case any one faced issues while parsing string date.
Generally we face two problems with dates
Parsing String to Date
Display Date in desired string format
DateTimeFormatter class in Java 8 can be used for both of these purpose.
Below methods try to provide solution to these issues.
Method 1:
Convert your UTC string to Instant. Using Instant you can create Date for any time-zone by providing time-zone string and use DateTimeFormatter to format date for display as you wish.
String dateString = "2016-07-13T18:08:50.118Z";
String tz = "America/Mexico_City";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
ZoneId zoneId = ZoneId.of(tz);
Instant instant = Instant.parse(dateString);
ZonedDateTime dateTimeInTz =ZonedDateTime.ofInstant(instant, zoneId);
System.out.println(dateTimeInTz.format(dtf));
Method 2:
Use DateTimeFormatter built in constants e.g ISO_INSTANT to parse string to LocalDate.
ISO_INSTANT can parse dates of pattern
yyyy-MM-dd'T'HH:mm:ssX e.g '2011-12-03T10:15:30Z'
LocalDate parsedDate
= LocalDate.parse(dateString, DateTimeFormatter.ISO_INSTANT);
DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy MM dd");
System.out.println(parsedDate.format(displayFormatter));
Method 3:
If your date string has much precision of time e.g it captures fraction of seconds as well as in this case 2016-07-13T18:08:50.118Z then method 1 will work but method 2 will not work. If you try to parse it will throw DateTimeException Since ISO_INSTANT formatter will not be able to parse fraction of seconds as you can see from its pattern.
In this case you will have to create a custom DateTimeFormatter by providing date pattern as below.
LocalDate localDate
= LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
Taken from a blog link written by me.
The Java 7 version of SimpleDateFormat supports ISO-8601 time zones using the uppercase letter X.
String string = "2011-04-15T20:08:18Z";
DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = iso8601.parse(string);
If you're stuck with Java 6 or earlier, the answer recommending JodaTime is a safe bet.
You have to give the following format:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date parse = simpleDateFormat.parse( "2011-04-15T20:08:18Z" );
I had a parse error in Andrew White solution.
Adding the single quote around the Z solved the issue
DateFormat m_ISO8601Local = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'");
the pattern in #khmarbaise answer worked for me, here's the utility method I extracted (note that the Z is omitted from the pattern string):
/**
* Converts an ISO-8601 formatted UTC timestamp.
*
* #return The parsed {#link Date}, or null.
*/
#Nullable
public static Date fromIsoUtcString(String isoUtcString) {
DateFormat isoUtcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
isoUtcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return isoUtcFormat.parse(isoUtcString);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
For all the older versions of JDK (6 down) it may be useful.
Getting rid of trailing 'Z' and replacing it literally with 'UTC' timezone display name - then parsing the whole string using proper simple date formatter.
String timeZuluVal = "2011-04-15T20:08:18Z";
timeZuluVal = timeZuluVal.substring( 0, timeZuluVal.length() - 2 ); // strip 'Z';
timeZuluVal += " " + TimeZone.getTimeZone( "UTC" ).getDisplayName();
DateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss zzzz" );
Date dateVal = simpleDateFormat.parse( timeZuluVal );
Joda Time
public static final String SERVER_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static DateTime getDateTimeFromUTC(String time) {
try {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(SERVER_TIME_FORMAT).withZoneUTC();
Calendar localTime = Calendar.getInstance();
DateTimeZone currentTimeZone = DateTimeZone.forTimeZone(localTime.getTimeZone());
return dateTimeFormatter.parseDateTime(time).toDateTime().withZone(currentTimeZone);
} catch (Exception e) {
return DateTime.now();
}
}