formatted string to date conversion without changing format in java - java

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.

Related

DateFormat format method doesn't display a parsed date to a particular TimeZone

I converted a date string to Date by SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(DateinString).
Here instead of converting to UTC it is converting to my Local TimeZone. I checked it by displaying this parsed date through format method of DateFormat.
So I have to re format it back to UTC.Now when I am trying to display this parsed date to UTC TimeZone through the same format method, it is still displaying in local TimeZone. Following is my code to format the parsed date to UTC-
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(alreadyParsedDateTime); //
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(cal.getTime()));
My sample date string is "2015-12-23T15:00:00-0800"
After parse -- alreadyParsedDateTime.toString():: Thu Dec 24 04:30:00 IST 2015
After parse --
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(alreadyParsedDateTime)):: 2015-12-24T04:30:00
After the above mentioned re format of the parsed date to UTC --
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(cal.getTime())):: 2015-12-24T04:30:00
Expected date format is:: 2015-12-23T23:00:00
I don't know why the format method not working in an expected way or there is any trick to do the same. Kindly help..
There are two different topics here; parsing and formatting.
1. Parsing
SimpleDateFormat.parse() will try to parse the timezone from the supplied date string. If the date string you are parsing does not include an explicit timezone, then the "default" timezone on the SimpleDateFormat object will be used. You can set the default time zone with the setTimeZone() method. Please see the API docs for SimpleDateFormat.parse() and DateFormat.setTimeZone() for reference.
Here is an example that shows how the parsing is influenced by the timezone set with setTimeZone():
String dateString = "2015.12.10 13:58:18";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date1 = sdf1.parse(dateString);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("EST"));
Date date2 = sdf2.parse(dateString);
// Shows that the parsing honours time zone -- will print:
// Thu Dec 10 14:58:18 CET 2015 (original date was parsed as GMT)
// Thu Dec 10 19:58:18 CET 2015 (original date was parsed as EST)
System.out.println(date1);
System.out.println(date2);
2. Formatting
Assuming that the date has been parsed correctly, then your problem is with the formatting. You need to set the timezone for the actual SimpleDateFormat object that you are using for formatting. I modified your code to do this and it will now print what you expet:
Calendar cal = Calendar.getInstance();
cal.setTime(alreadyParsedDateTime);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf3.setTimeZone(TimeZone.getTimeZone("UTC"));
// Prints: 2015-12-23T23:00:00 for your example date string
System.out.println(sdf3.format(cal.getTime()));
tl;dr
Current moment in UTC.
Instant.now() // Capture current moment in UTC.
.toString() // Generate string in standard ISO 8601 format.
2018-02-11T22:13:28.650328Z
Adjust into another time zone.
instant.atZone( // Apply a `ZoneId` to `Instant` object to get a `ZonedDateTime` object.
ZoneId.of( "Pacific/Auckland" )
).toString()
2018-02-12T11:13:28.650328+13:00[Pacific/Auckland]
Or capture current moment directly into that zone.
ZonedDateTime.now( // Capture current moment as seen on the wall-clock time of the people in a particular region.
ZoneId.of( "Pacific/Auckland" )
).toString() // Generate string in standard ISO 8601 format, wisely extended by appending the name of the time zone in square brackets.
2018-02-12T11:13:28.650328+13:00[Pacific/Auckland]
Details
The Answer by Grodriguez is correct but outdated.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
Your input string complies with the ISO 8601 formatting standard. The java.time classes use these formats by default when parsing/generating strings. So no need to specify a formatting pattern.
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).
Capture the current moment in UTC.
Instant instant = Instant.now() ; // Current moment in UTC.
To view that same simultaneous moment through the lens of a wall-clock time used by the people of another region (time zone), apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Note that we are working with smart objects here, not dumb strings. Do not conflate the date-time objects with mere strings that may represent their values textually.
If you want to generate a String in standard ISO 8601 format, call the toString method.
String outputA = instant.toString() ;
String outputB = zdt.toString() ;
To generate strings in other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Both are covered extensively on Stack Overflow, so search for more info.
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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.

Date time String + TimeZone

I have a String representation of a local date time, and a Java TimeZone.
I am trying to get output in the format MM/dd/yyyy HH:mm:ssZ but I can't figure out how to create a Calendar or JodaTime object with the correct date time and timezone. How do you get a TimeZone converted to a value that can be parsed by SimpleDateFormat 'Z' or 'z'?
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
String startDate = "08/14/2014 15:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance(tz);
cal.setTime(sdf.parse(startDate));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ");
and
sdfZ.format(cal.getTime())
returns
08/14/2014 15:00:00-0400
which is EST.
Is the only workaround to create a Calendar or Joda DateTime and set the individual year/month/day/hour/min values by parsing the string "08/14/2014 15:00:00" ?
Calendar getTime() - Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(01-01-1970 00:00 GMT)") irrespective of which timezone you are displaying. But hour of day in different TimeZone will be different. get(Calendar.HOUR_OF_DAY)
You should try
sdfZ.setTimeZone(tz);
tl;dr
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Chicago" ) ) ;
String output = zdt.toInstant().toString() ;
2016-12-03T10:15:30Z
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Call toString to generate a String in standard ISO 8601 format. For example, 2011-12-03T10:15:30Z. This format is good for serializing date-time values for data storage or exchange.
String output = instant.toString(); // Ex: 2011-12-03T10:15:30Z
Time zone
Assign a time zone.
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
As a shortcut, you can skip over using Instant.
ZonedDateTime zdt = ZonedDateTime.now( z );
Calling toString on ZonedDateTime gets you an extended version of standard ISO 8601 format where the name of the time zone is appended in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
String output = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
DateTimeFormatter
The DateTimeFormatter class has a predefined formatter constant for your desired output: DateTimeFormatter.ISO_LOCAL_DATE_TIME
String output zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME );
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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.

Android: How to Format Date and Time Strings correctly?

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

Conversion of string with AM/PM date-time, from Oracle database

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.

How can I parse UTC date/time (String) into something more readable?

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();
}
}

Categories