String date="2006-06-21T15:57:24.000Z";
How do I convert this String to a Date object without changing this format in Android?
Here simple code for this:
private Date parseDate(String date) {
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S'Z'");
Date dateObj = new Date();
try {
dateObj = curFormater.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateObj;
}
Use the Time class and parse the string. Then use the Time toMillis() function and instantiate a Date.
http://developer.android.com/reference/android/text/format/Time.html#parse3339(java.lang.String)
See SimpleDateFormat, http://developer.android.com/reference/java/text/SimpleDateFormat.html
This class converts Strings to Dates and vice versa, using a given pattern.
Once you have created a SimpleDateFormat with the right pattern, you can use it to convert the string to a Date, use the date as you like, and eventually convert the Date back to a String using that same SimpleDateFormat instance.
EDIT: clarification on time zones
In the question it is not specified wether the given string is a "pure" ISO 8601 date, and in that case whether you need or not to support multiple time zones, if that timezones will be represented as only numbers (+0200 as in RFC 822), numbers with a colon (+02:00 as permitted by ISO 8601) or as names (EST etc...).
In case the string is a pure ISO 8601 String, then SimpleDateFormat will have some problems decoding the time zone. If however it is "always Z" (meaning that timezone data is not meaningful and you can safely ignore it), or uses numbers without colon (like +0200 etc..), or uses time zone names, then SimpleDateFormat can handle it correctly.
I came here because this was supposedly an answered question of Covert RFC3339 DateTime to Date in java. However, Time is a deprecated class in Android since API level 22.
A simple answer is based on this one:
import com.google.api.client.util.DateTime;
Date date = new Date(new DateTime("2006-06-21T15:57:24.000Z").getValue());
tl;dr
How do I convert this String to a Date object
Date is supplanted by java.time.Instant.
Instant.parse( "2006-06-21T15:57:24.000Z" )
without changing this format
Date-time objects do not have a “format”. Only text has a format.
String output = instant.toString() ; // Generate text in a `String` object in standard ISO 8601 format that represents the value of the `Instant` date-time object.
ISO 8601
That input string happens to be in standard ISO 8601 format. The Z on the end is short for Zulu and means UTC.
java.time
The java.time classes use ISO 8601 formats by default when parsing and generating strings that represent date-time values.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2006-06-21T15:57:24.000Z" );
To generate a String in standard ISO 8601 format, call toString.
String output = instant.toString();
2006-06-21T15:57:24Z
String != date-time
Do not conflate a date-time object with a String representing the value. The date-time object can parse a String, and can generate a String, but is not the String. In other words, a String can be input and/or output but is not the date-time object itself.
So your question, “How do I convert this String to a Date object without changing this format” makes no sense.
To generate a String in formats other than ISO 8601, convert your Instant to an OffsetDateTime or ZonedDateTime object, and use the DateTimeFormatter class. Search Stack Overflow for DateTimeFormatter to see more discussion and many examples.
Conversion
You should avoid the old java.util.Date class whenever possible. But if you must interface with old code not yet updated to the java.time types, you may convert to/from java.time via new methods added to the old date-time classes.
java.util.Date utilDate = java.util.Date.from( instant );
…and going the other direction…
Instant instant = utilDate.toInstant();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Related
String formatA ="yyyy-MM-dd'T'HH:mm:ss'Z'";
String formatB = "dd/MM/yyyy HH:mm:ss.SSS";
try {
XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat(formatB).format(new Date()));
System.out.println(gregFmt);
} catch (DatatypeConfigurationException e) {
};
I am trying to formate XMLGregorianCalendar date .
The above code formats well for format "yyyy-MM-dd'T'HH:mm:ss'Z'"
But for formatB dd/MM/yyyy HH:mm:ss.SSS it throws error
java.lang.IllegalArgumentException
Do advice on how to fix it. Thank you so much!
log
Exception in thread "main" java.lang.IllegalArgumentException: 23/08/2017 16:13:04.140
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parseAndSetYear(XMLGregorianCalendarImpl.java:2887)
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parse(XMLGregorianCalendarImpl.java:2773)
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.<init>(XMLGregorianCalendarImpl.java:435)
at com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl.newXMLGregorianCalendar(DatatypeFactoryImpl.java:536)
at test.test.main(test.java:19)
line19 is line 4 , in the above code 'XMLGregorianCalendar gregFmt...'
The format that newXMLGregorianCalendar(string) accept is described in the XML specs and is different from the formatB you are trying to use.
tl;dr
Date-time objects do not have a “format”. They parse & generate String objects representing textually their value.
Use the modern java.time that replaced terrible old classes Date & XMLGregorianCalendar classes.
Example:
myXMLGregorianCalendar // If you must use this class… but try to avoid. Use *java.time* classes instead.
.toGregorianCalendar() // Converting from `javax.xml.datatype.XMLGregorianCalendar` to `java.util.GregorianCalendar`.
.toZonedDateTime() // Converting from `java.util.GregorianCalendar` to `java.time.ZonedDateTime`, from legacy class to modern class.
.format( // Generate a `String` representing the moment stored in our `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss.SSS" ) // Define a formatting pattern as you desire. Or better, automatically localize by calling `DateTimeFormatter.ofLocalized…` methods.
) // Returns a `String` object, distinct from our `ZonedDateTime` object.
07/07/2018 15:20:14.372
Date-time objects do not have a format
Do not conflate date-time objects with the strings they generate to represent their value. Date-time values, including the classes discussed below, are not a String, do not use text as their internal value, and do not have a “format”. All of them can generate, and parse, strings to represent their date-time value.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as XMLGregorianCalendar.
The use of java.util.Date should be replaced with java.time.Instant. Both represent a moment in UTC. Instant uses a finer resolution of nanoseconds rather than milliseconds.
You can easily convert between the modern and legacy classes. Notice the new conversion methods added to the old classes, in this case java.util.GregorianCalendar::toZonedDateTime.
First convert from javax.xml.datatype.XMLGregorianCalendar to java.util.GregorianCalendar.
GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
Now get out of these legacy classes, and into java.time.
ZonedDateTime zdt = gc.toZonedDateTime() ;
All three types so far, the XMLGregorianCalendar, the GregorianCalendar, and the ZonedDateTime all represent the same moment, a date with time-of-day and an assigned time zone.
With a ZonedDateTime in hand, you can generate a String in standard ISO 8601 format extended to append the name of the time zone in square brackets.
String output = zdt.toString() ; // Generate string in standard ISO 8601 format extended by appending the name of time zone in square brackets.
2018-07-07T15:20:14.372-07:00[America/Los_Angeles]
You can generate strings in other formats using DateTimeFormatter class. For the formatting pattern listed second in your question, define a matching DateTimeFormatter object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss.SSS" ) ;
String output = zdt.format( f ) ;
07/07/2018 15:20:14.372
The first formatting pattern listed in your Question has a Z on the end, which means UTC and is pronounced “Zulu”. To adjust our ZonedDateTime to UTC, simply extract a Instant object. An Instant is always in UTC by definition.
Instant instant = zdt.toInstant() ; // Extract an `Instant` object, always in UTC.
Generate a String in the pattern shown first in the Question.
String output = instant.toString() ; // Generate string in standard ISO 8601 format.
2018-07-07T22:20:14.372Z
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 am trying to convert the date in milliseconds to the following ISO 8601 format:
But I am getting the following using SimpleDateFormat:
/**
* It converts the time from long to the ISO format
*
* #param timestampMillis
* #return isoDate
*/
public String convertTimeMillisToISO8601(String timestampMillis)
{
long timeInLong= Long.parseLong(timestampMillis);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String isoDate = df.format(new java.util.Date(timeInLong));
return isoDate;
}
OUTPUT:
"ts":"2015-06-18T09:56:21+0000"
I know I can use substring to append the extra colon but Is there any better way to do so ?
For Java 7 and higher, you might use XXX (ISO 8601 time zone) in the date format String. According to the documentation, the result of X can be:
X => -08
XX => -0800
XXX => -08:00
but for all of those, it might as well return Z!
For Java 6 and earlier, there is no X (J6 doc), and since the result of X may or may not do what you want, I strongly recommend you just insert that colon yourself.
You can always use a StringBuilder:
new StringBuilder(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.format(date))
.insert(22,':')
.toString();
For Java 8 if you use one of the standard ISO_DATE_* format patterns then the output formatted String will be truncated when the offset is +00:00 (UTC typically just appends Z).
OffsetDateTime utcWithFractionOfSecond = ZonedDateTime.parse("2018-01-10T12:00:00.000000+00:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME);
utcWithFractionOfSecond.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); // 2018-01-10T12:00:00Z ... not what you want!
The only solution I have found is using the outputPattern (shown below) that uses lowercase `xxx' to ensure that a colon is included in the timezone offset.
I have included an example with factions-of-a-second for completeness (you can remove the SSSSSS in your case)
DateTimeFormatter inputPattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
DateTimeFormatter outputPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSxxx");
OffsetDateTime utcWithFractionOfSecond = OffsetDateTime.parse("2018-01-10T12:00:00.000000+00:00", inputPattern);
OffsetDateTime utcNoFractionOfSecond = OffsetDateTime.parse("2018-01-10T12:00:00+00:00", inputPattern);
OffsetDateTime utcWithZ = OffsetDateTime.parse("2018-01-10T12:00:00Z", inputPattern);
OffsetDateTime utcPlus3Hours = OffsetDateTime.parse("2018-01-10T12:00:00.000000+03:00", inputPattern);|
utcWithFractionOfSecond.format(outputPattern ); // 2018-01-10T12:00:00.000000+00:00
utcNoFractionOfSecond.format(outputPattern); // 2018-01-10T12:00:00.000000+00:00
utcWithZ.format(outputPattern); // 2018-01-10T12:00:00.000000+00:00
utcPlus3Hours.format(outputPattern); // 2018-01-10T12:00:00.000000+03:00
In these examples I have used ISO_OFFSET_DATE_TIME only to create the input values for the test cases. In all cases it is the outputPattern yyyy-MM-dd'T'HH:mm:ss.SSSSSSxxx that controlling how to include a colon character in the timezone portion of your resulting formatted string.
Note that if your input data included the Zone ID like [Europe/London] then you would create your input data using ZonedDateTime instead of OffsetDateTime
Can you use Java 8?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ssXXX");
System.out.println(formatter.format(ZonedDateTime.now()));
2015-04-15T17:24:19+09:00
tl;dr
OffsetDateTime.parse( "2014-06-18T09:56:21+00:00" )
2014-06-18T09:56:21Z
Details
Some other answers are close, correct in using the modern java.time classes that supplanted the terrible old legacy classes (Date, Calendar, SimpleDateFormat). But they are either working too hard or chose the wrong class.
ISO 8601
Your format is in standard ISO 8601 format. The java.time classes use these standard formats by default when parsing/generating text representing their date-time values. So you need not specify any formatting pattern at all. Works by default.
OffsetDateTime
Your input indicates an offset-from-UTC of zero hours and zero minutes. So we should use the OffsetDateTime class.
String input = "2014-06-18T09:56:21+00:00";
OffsetDateTime odt = OffsetDateTime.parse( input );
Zulu time
We can generate a string in standard ISO 8601 format by merely calling toString. The Z on the end means UTC, and is pronounced “Zulu”.
odt.toString(): 2014-06-18T09:56:21Z
ZonedDateTime
If your input indicated a time zone, rather than merely an offset, we would have used ZonedDateTime class. An offset is simply a number of hours, minutes, and seconds – nothing more. A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region.
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.
I used the below code where I've printed the modified GMT date in String & in Date format, it's giving me two different values.
Date initial = new Date();
DateFormat dateFormatter = DateFormat.getInstance();
dateFormatter.setTimeZone (TimeZone.getTimeZone("UTC"));
String gmtS = dateFormatter.format(initial);
Date gmt = dateFormatter.parse(gmtS);
System.out.println("Data type is Date = " + gmt);
System.out.println("Data type is String "+gmtS);
Output
gtm where value id of type Date = Thu Jul 03 23:15:00 EDT 2014
gmtS where value id of type String = 7/4/14 3:15 AM
But I want to see the value (7/4/14 3:15 AM) as a Date type.
Any help is really appreciated.
When you output a Date by calling toString() (which is what System.out.println("Data type is Date = " + gmt); does) you will get that Date according to the system time zone, because that is what Date.toString() returns.
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
where:
...
zzz is the time zone (and may reflect daylight saving time). Standard time
zone abbreviations include those recognized by the method parse. If time
zone information is not available, then zzz is empty - that is, it
consists of no characters at all.
So, to get the output you expect use your dateFormatter to format it again.
String gmtS = dateFormatter.format(initial);
Date gmt = dateFormatter.parse(gmtS);
System.out.println("Data type is Date = " + dateFormatter.format(gmt));
tl;dr
Instant.now().toString()
2019-02-07T19:15:29.123456Z
Avoid legacy date-time classes
You are using date-time classes that are terribly troublesome, with many flaws in design.
First, you should know that java.util.Date represents a moment in UTC, always in UTC by definition. But its toString method tells a lie, dynamically applying the JVM’s current default time zone while generating the text representing the moment in the Date object.
java.time
The modern approach uses the java.time classes.
Instant
For a moment in UTC, use Instant. Like java.time.Date it represents a moment always in UTC (but with a finer resolution of nanoseconds versus milliseconds). Indeed, you can convert easily back-and-forth between Date and Instant by using new methods added to the old class.
Unlike toString on Date, the toString method on Instant always tells the truth. The method generates text in standard ISO 8601 format. The T in the middle separates the date portion from the time portion. The Z on the end is short for UTC and is pronounced “Zulu”.
Instant.now().toString(): 2019-01-23T12:34:56.123456789Z
OffsetDateTime
The Instant class is a basic building-block class in java.time, with limited functionality. If you want more flexible formatting, use the OffsetDateTime class with the offset set to UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
Or skip the Instant class.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
To generate text representing the value of the OffsetDateTime object, use the DateTimeFormatter class. Search Stack Overflow as this has been covered many many times already.
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.
I'm using struts2.x with jquery date picker.
I want to dispaly in the format dd/mm/yyyy. But from the database when fetching it is coming like yyyy-mm-dd.Then i converted it into the required format but the type is String. So next i Converted it to Date type. But the format is changed.
Date getRiskCommDate()
{
String fString = null;
System.out.println("Coming Date from DB"+riskCommDate);
if(riskCommDate!=null)
{
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("dd/MM/yyyy");
fString = format.format(riskCommDate);
}
System.out.println("Formated Date in String Form "+fString);
Date d = new Date(fString);
System.out.println("Formated Date in Date form Date "+d);
return d;
}
Output :
Coming Date from DB 2012-07-04
Formated Date in String Form 04/07/2012
Formated Date in Date form Date Sat Apr 07 00:00:00 IST 2012
Any idea is highly appreciated.
The java.util.Date class does not have any property to hold a format.
To display the value of the Date in a custom format, call the format method on SimpleDateFormat.
When you do this:
System.out.println(dateInstance)
…you are simply calling the toString() on the Date. That method returns the date in fixed format in String version.
Based on the comments
If you anyhow wants the custom format with date instance then you can either create a custom class wrapping date instance
class MyDate{
private Date date;
//provide appropriate accessor
//override toString() method to support required output
}
or extend Date
class MyDate extends Date{
//override toString() method to support required output
#Override
public String toString(){
//convert `this` to String with required format with the help of `SimpleDateFormat`
}
}
Date prints a format based on the Locale. It doesn't "remember" the format you gave it want you constructed it. Only Strings have a particular format, so if you need that, keep it as a String.
java.time
The old troublesome date-time libraries bundled with early Java have been supplanted by the java.time framework built into Java 8 and later. For Java 6 & 7, use the back-port, ThreeTen-Backport, and for Android the adaption thereof, ThreeTenABP. Avoid using the old java.util.Date/.Calendar and such.
LocalDate
The java.time classes include LocalDate for a date-only value without time-of-day and without time zone.
java.sql.Date
Hopefully JDBC drivers will be updated to deal directly with java.time types. Until then, use java.sql types for moving data in/out of database. The old java.sql classes have new to… and valueOf methods for conversion with java.time. Our interest here is in java.sql.Date.
LocalDate localDate = myJavaSqlDate.toLocalDate();
You can go the other direction, for submission to the database.
java.sql.Date myJavaSqlDate = java.sql.Date.valueOf( localDate );
Generate String
None of the discussed date classes (java.util.Date, java.sql.Date, java.time.LocalDate) have any “format”. Only textual representations of their values have a format. If you need a String, those classes can generate a String object for you. But do not confuse that String object with a date-time object as they are entirely separate and distinct.
The toString method on LocalDate use standard ISO 8601 format such as 2012-07-04 (meaning July 4, 2012).
String outputIso8601 = localDate.toString();
For other formats, use a DateTimeFormatter. Many other Questions and Answers on Stack Overflow have more discussion.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
String output = localDate.format( formatter ); // Generates a textual representation of the object’s date-only value.
Better yet, let java.time localize for you.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT );
formatter = formatter.withLocale( Locale.CANADA_FRENCH ); // or Locale.US, and so on.
String output = localDate.format( formatter );
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.
Is there a straightforward way of converting a Java SQL Date from format yyyy-MM-dd to dd MMMM yyyy format?
I could convert the date to a string and then manipulate it but I'd rather leave it as a Java SQL Date. at the time I need to do this, the data has already been read from the MySQL database so I cant do the change there.
Object such as java.sql.Date and java.util.Date (of which java.sql.Date is a subclass) don't have a format of themselves. You use a java.text.DateFormat object to display these objects in a specific format, and it's the DateFormat (not the Date itself) that determines the format.
For example:
Date date = ...; // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);
Note: When you print a Date object without using a DateFormat object, like this:
Date date = ...;
System.out.println(date);
then it will be formatted using some default format. That default format is however not a property of the Date object that you can change.
If it is for presentation you can use SimpleDateFormat straight away:
package org.experiment;
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Dates {
private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");
public static void main(String[] args){
Date oneDate = new Date(new java.util.Date().getTime());
System.out.println(df.format(oneDate));
}
}
It's not clear what you mean by a "Java SQL Date". If you mean as in java.sql.Date, then it doesn't really have a string format... it's just a number. To format it in a particular way, use something like java.text.SimpleDateFormat.
Alternatively, convert it to a Joda Time DateTime; Joda Time is a much better date and time API than the built-in one. For example, SimpleDateFormat isn't thread-safe.
(Note that a java.sql.Date has more precision than a normal java.util.Date, but it looks like you don't need that here.)
tl;dr
myJavaSqlDate.toLocalDate()
.format(
DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG )
.withLocale ( Locale.UK )
)
11 May 2017
Do not conflate date-time values with their textual representation
As others said, a date-time object has no format. Only strings generated from the object or parsed by the object have a format. But such strings are always separate and distinct from the date-time object.
Use objects, not strings
Avoid using strings to communicate date-time values to/from your database. For date-time values, use date-time classes to instantiate date-time objects.
The very purpose of JDBC is to mediate the differences in types between your database and Java.
Using java.time
The other Answers are outdated as they use the troublesome old legacy date-time classes or the venerable Joda-Time library. Both have been supplanted by the java.time classes.
If you have a java.sql.Date object in hand, convert to java.time.LocalDate by calling the new method toLocalDate added to the old class.
LocalDate ld = myJavaSqlDate.toLocalDate() ;
For JDBC drivers that comply with JDBC 4.2 and later, you can work directly with java.time types.
You seem to be interested in the date-only values. So use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
PreparedStatement::setObjectmyPStmt.setObject( … , myLocalDate )
ResultSet::getObjectmyResultSet.getObject( … , LocalDate.class )
To generate a string in your desired format, you could specify a custom formatting pattern. But I suggest letting 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…
LocalDate ld = LocalDate.now ( ZoneId.of ( "America/Montreal" ) ); // Today's date at this moment in that zone.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.UK );
String output = ld.format ( f );
output: 11 May 2017
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
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.