This question already has answers here:
Java string to date conversion
(17 answers)
Closed 4 years ago.
I have a string in this format
String oldstring = "Mar 19 2018 - 14:39";
How to convert this string to java object so that I get time and mins from date object.
I have tried like this,
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateEg {
public static final void main(String[] args) {
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");
String oldstring = "Mar 19 2018 - 14:39";
String time = localDateFormat.format(oldstring);
System.out.println(time);
}
}
But getting error, saying Cannot format given Object as a Date
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.base/java.text.DateFormat.format(DateFormat.java:332)
at java.base/java.text.Format.format(Format.java:158)
at DateEg.main(DateEg.java:9)
Is it possible to parse this string format in java?
User proper formatter with your code to parse string mentioned below
SimpleDateFormat localDateFormat = new SimpleDateFormat("MMM dd yyyy - HH:mm");
String oldstring = "Mar 19 2018 - 14:39";
Date date=localDateFormat.parse(oldstring);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
tl;dr
LocalDateTime.parse( // Parse as a `LocalDateTime` because the input lacks indication of zone/offset.
"Mar 19 2018 - 14:39" ,
DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , Locale.US )
) // Returns a `LocalDateTime` object.
.toLocalTime() // Extract a time-of-day value.
.toString() // Generate a String in standard ISO 8601 format.
14:39
java.time
The modern approach uses the java.time classes.
Define a formatting pattern to match your input. Specify Locale to determine human language and cultural norms used in parsing this localized input string.
String input = "Mar 19 2018 - 14:39" ;
Locale locale = Locale.US ; // Specify `Locale` to determine human language and cultural norms used in parsing this localized input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , locale ) ;
Parse as a LocalDateTime because the input lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f );
Extract the time-of-day value, without a date and without a time zone, as that is the goal of the Question.
LocalTime lt = ldt.toLocalTime();
ldt.toString(): 2018-03-19T14:39
lt.toString(): 14:39
ISO 8601
The format of your input is terrible. When serializing date-time values as text, always use standard ISO 8601 formats.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings. You can see examples above in this Answer.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try using this, this should work:
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM dd yyyy - HH:mm");
LocalDateTime dt = formatter.parse(oldstring);`
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
String time = timeFormat.format(dt).toString();`
If you can use an external library, the Apache Common DateUtils provides many utility classes that you can use to work on dates.
In order to parse your string to an object you can use for instance:
public static Date parseDate(String str, Locale locale, String... parsePatterns) throws ParseException
Parses a string representing a date by trying a variety of different
parsers, using the default date format symbols for the given locale.
The parse will try each parse pattern in turn. A parse is only deemed
successful if it parses the whole of the input string. If no parse
patterns match, a ParseException is thrown.
The parser will be lenient toward the parsed date.
Parameters:str - the date to parse, not nulllocale - the locale whose
date format symbols should be used. If null, the system locale is used
(as per parseDate(String, String...)).parsePatterns - the date format
patterns to use, see SimpleDateFormat, not nullReturns:the parsed
dateThrows:IllegalArgumentException - if the date string or pattern
array is nullParseException - if none of the date patterns were
suitable (or there were none)Since:3.2
Related
How convert this string to dateTime?
2016-01-09 21:04:56.0
I tried
private Date getDate(CallDetail callDetail) {
Date date = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
date = simpleDateFormat.parse(callDetail.getStarttime());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
But I have error:
Unparseable date: "2016-01-09 21:04:56.0"
I do not know how trim .0
Your format string has to represent the string you want to parse.
E.g. if you want to parse 25.12.2015 your format string has to be "dd.MM.yyyy".
With that being said, your format string to parse the given date should be "yyyy-MM-dd HH:mm:ss:S"
If you just want to get rid of the milliseconds you could either parse the date and format it it afterwards:
String toParse = "2016-01-09 21:04:56.0";
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date newDate = sdfIn.parse(toParse);
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
toParse = sdfOut.format(newDate);
or just cut off the milliseconds with substring():
String toParse = "2016-01-09 21:04:56.0";
toParse = toParse = toParse.substring(0, toParse.lastIndexOf("."));
Try using below format "yyyy-MM-dd hh:mm:ss.S"
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.S");
Date date = simpleDateFormat.parse("2016-01-09 21:04:56.0");
System.out.println(date);
}
output
Sat Jan 09 21:04:56 IST 2016
The modern way is with the java.time classes and standard ISO 8601 formats.
ISO 8601
The ISO 8601 standard defines many formats for representing date-time values as text. For a date with time-of-day, the format is YYYY-MM-DDTHH:MM:SS.s.
The java.time classes use these standard formats by default when parsing and generating strings.
Your input string can be made to comply easily. Replace the SPACE in the middle with a T.
String input = "2016-01-09 21:04:56.0".replace( " " , "T" );
LocalDateTime
Your input string lacks any indication of time zone or offset-from-UTC. So we parse as a LocalDateTime object.
LocalDateTime ldt = LocalDateTime.parse( input );
Your goal seems to be generating a string of this date-time value without the fractional second if zero. The LocalDateTime class does this by default, printing zero, three, six, or nine digits of fractional second, the least needed.
String output = ldt.toString();
2016-01-09T21:04:56
For your desired format, replace the T with a SPACE.
String output2 = output.replace( "T" , " " );
A LocalDateTime intentionally lacks any time zone. As such, it does not represent a moment on the timeline. That requires the context of a time zone.
Truncation
If you want to get rid of the fractional second, truncate.
LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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 want to parse a date, which was created with a specific timezone, convert it to a format and return it. The conversion works but the timezone offset is always set to +0000 with the time difference being added/subtracted as necessary. How can I get it to format and keep the offset correct?
I expect this: 2012-11-30T12:08:56.23+07:00
But get this: 2012-11-30T05:08:56.23+00:00
Implementation:
public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSZZ";
public static String formatDateToISO8601Standard(Date date) {
DateTime dateTime = new DateTime(date);
DateTimeFormatter df = DateTimeFormat.forPattern(ISO_8601_DATE_FORMAT);
return dateTime.toString(df);
}
Test class:
private static final String DATE_WITH_TIMEZONE = "30 11 2012 12:08:56.235 +0700";
private static final String EXPECTED_DATE_WITH_TIMEZONE = "2012-11-30T12:08:56.23+07:00";
#Test public void testFormattingDateWithSpecificTimezone() throws Exception {
String result = JodaDateUtil.formatDateToISO8601Standard(createDate(DATE_WITH_TIMEZONE));
assertEquals("The date was not converted correctly", EXPECTED_DATE_WITH_TIMEZONE, result); }
private Date createDate(String dateToParse) throws ParseException {
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.parseDateTime(dateToParse);
Date date = temp.toDate();
return date; }
Basically, once you parse the date string [in your createDate() method] you've lost the original zone. Joda-Time will allow you to format the date using any zone, but you'll need to retain the original zone.
In your createDate() method, the DateTimeFormatter "df" can return the zone that was on the string. You'll need to use the withOffsetParsed() method. Then, when you have your DateTime, call getZone(). If you save this zone somewhere or somehow pass it to your formatting routine, then you can use it there by creating a DateTimeFormatter "withZone" and specifying that zone as the one you want on the format.
As a demo, here's some sample code in a single method. Hopefully, it'll help change your code the way you want it to run.
public static void testDate()
{
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.withOffsetParsed().parseDateTime("30 11 2012 12:08:56.235 +0700");
DateTimeZone theZone = temp.getZone();
Date date = temp.toDate();
DateTime dateTime = new DateTime(date);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
DateTimeFormatter df3 = df2.withZone(theZone);
System.out.println(dateTime.toString(df2));
System.out.println(dateTime.toString(df3));
}
tl;dr
OffsetDateTime.parse (
"30 11 2012 12:08:56.235 +0700" ,
DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US )
).toString()
2012-11-30T12:08:56.235+07:00
Details
The accepted Answer is correct. As soon as you convert to a java.util.Date object, you lose time zone information. This is complicated by the fact that java.util.Date::toString confusingly applies a current default time zone when generating the String.
Avoid using these old date-time classes like java.util.Date. They are poorly-designed, confusing, and troublesome. Now legacy, supplanted by the java.time project. So too is the Joda-Time project now supplanted by the java.time classes.
java.time
Parse that input string as a OffsetDateTime object as it includes an offset-from-UTC but lacks a time zone. Call DateTimeFormatter.ofPattern to specify a custom format matching your input string. Pass that formatter object to OffsetDateTime.parse.
String input = "30 11 2012 12:08:56.235 +0700" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
odt:toString(): 2012-11-30T12:08:56.235+07:00
To see the same moment in UTC, extract 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 = odt.toInstant();
instant.toString(): 2012-11-30T05:08:56.235Z
You can apply any time zone through which you want to view the same moment, the same point on the timeline.
ZonedDateTime zdtKolkata = odt.toInstant ().atZone ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata.toString(): 2012-11-30T10:38:56.235+05:30[Asia/Kolkata]
No need to mix in the old date-time classes at all. Stick with java.time. If you must use some old code not yet updated to java.time types, look to new methods added to the old classes to convert to/from java.time.
The equivalent of java.util.Date is Instant, both being a count-since-epoch of 1970-01-01T00:00:00Z in UTC. But beware of data-loss as the java.time classes support nanosecond resolution but the old classes are limited to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant );
Live code
See live working code in IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & 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. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try this.
ISODateTimeFormat.dateTimeParser().parseDateTime(dateString),
then convert that to the format you desire.
Use the format
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSZZ")
I need to convert a String containing date into an date object. The String will be of the format "yyyy-mm-dd HH:mm:ss.SSSSSS" and I want the same format in an date object.
For instance I have a string "2012-07-10 14:58:00.000000", and I need the resultant date object to be of the same format.
I have tried the below methods but, the resultant is not as expected.
java.util.Date temp = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date thisDate = dateFormat.parse("2012-07-10 14:58:00.000000");
The result is "Tue Jan 10 14:58:00 EST 2012". Please let me know where I am going wrong.
Thanks,
Yeshwanth Kota
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
The mm is minutes you want MM
CODE
public class Test {
public static void main(String[] args) throws ParseException {
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse("2012-07-10 14:58:00.000000");
System.out.println(temp);
}
}
Prints:
Tue Jul 10 14:58:00 EDT 2012
For future reference:
yyyy => 4 digit year
MM => 2 digit month (you must type MM in ALL CAPS)
dd => 2 digit "day of the month"
HH => 2-digit "hour in day" (0 to 23)
mm => 2-digit minute (you must type mm in lowercase)
ss => 2-digit seconds
SSS => milliseconds
So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"
But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"
The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!
tl;dr
LocalDateTime.parse(
"2012-07-10 14:58:00.000000".replace( " " , "T" )
)
Microseconds do not fit
You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.
Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).
Unzoned input does not fit a zoned type
You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.
Use an appropriate data type instead. Specifically, java.time.LocalDateTime.
Case-sensitive
Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM and mm have different effects.
Avoid legacy classes
The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.
ISO 8601
Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T to comply fully.
The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Date-time objects have no "format"
and I need the resultant date object to be of the same format.
No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.
java.time
Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime objects which lacks those concepts.
String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Generating strings
To generate a String representing the value of your LocalDateTime:
Call toString to get a String in standard ISO 8601 format.
Use DateTimeFormatter for producing strings in either custom formats or automatically-localized formats.
Search Stack Overflow for more info as these topics have been covered many many times already.
ZonedDateTime
A LocalDateTime does not represent an exact point on the timeline.
To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Your not applying Date formator. rather you are just parsing the date. to get output in this format
yyyy-MM-dd HH:mm:ss.SSSSSS
we have to use format() method here is full example:-
Here is full example:-
it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS
and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");
System.out.println(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(temp);
System.out.println(strDateOutput);
}
}
its work for me
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.format(new Date));
I am trying to parse datetime string with SimpleDateFormat.parse() but I keep receiving Unparseable date exceptions.
Here is the date format I am trying to parse: 2011-10-06T12:00:00-08:00
Here is the code I am using:
try {
String dateStr = "2011-10-06T12:00:00-08:00";
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM d, yyyy");
Date date = dateParser.parse(dateStr);
System.out.println(dateFormatter.format(date));
} catch(Exception e) {
System.out.println(e.getMessage());
}
Which returns this error: java.text.ParseException: Unparseable date: "2011-10-06T12:00:00-08:00"
As far as I know this is the correct way to use the SimpleDateFormat class but I'm not fluent in Java so I could be mistaken. Any one know what my issue is?
The timezone should be GMT-08:00 or -0800 (as Madcore Tom said). See Java docs.
In Java 7 you can use "yyyy-MM-dd'T'HH:mm:ssX"
I believe that SimpleDateFormat will not parse timezones with a colon in them (-08:00). It should be able to parse the date 2011-10-06T12:00:00-0800.
Some simple string manipulation should help you get rid of the colon.
You first need to format the value in "2011-10-06T12: 00: 00-08: 00".
Example: SimpleDateFormat dateParser = new SimpleDateFormat ("yyyy-MM-dd'T'HH: mm: ssZ");
After, create the formating for formataction desired.
Ex: SimpleDateFormat fmt = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss");
and after make parse for date.
Ex: Date date = dateParser.parse (dateFormat);
and print of date formated.
Below, one complete example.
String dataStr = "2011-10-06T12: 00: 00-08: 00";
SimpleDateFormat dataParser = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss", Locale.US);
Date date;
Try {
date = dataParser.parse (dataStr);
System.out.println (dateFormatter.format (date));
} cath (ParseException e) {
}
tl;dr
OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" )
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ) // Or Locale.CANADA_FRENCH and such.
)
Oct 6, 2011
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
You input string is in a format that complies with the ISO 8106 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Parse as an OffsetDateTime because your input strings includes an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" ) ;
odt.toString(): 2011-10-06T12:00-08:00
Generate a string in your desired format. Let java.time automatically localize rather than hard-code formatting patterns.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ); // Or Locale.CANADA_FRENCH and such.
String output = odt.format( f );
output: Oct 6, 2011
When seralizing a date-time value as text, use the standard ISO 8601 formats rather than a localized format.
String output = odt.toLocalDate().toString() ;
2011-10-06
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time 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.
Try with
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
For a date format like 2013-06-28T00:00:00+00:00, this code should work:
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
I am sure most of you got frustrated from the fact that SimpleDateFormat can not handle ISO8601 format. Here is my little trick to solve this nuisance.
Create a list of Know format you know that you will use for your application and apply SimpleDateFormat to the list. Now, in your formatDate() method, simple try all your known format and trap the Exception, then if still did not have a date, just use
Date d = javax.xml.bind.DatatypeConverter.parseDateTime("2013-06-28T00:00:00+00:00").getTime();
if (d == null)
try {
SimpleDateFormater ...
}
to try it and see if that work. For more info Simple trick to convert Date format with timezone in Java!
I'd strongly recommend using JodaTime for this sort of thing.
You're trying to parse an ISO Date format, and Joda does that 'out of the box', and will give you plenty of other benefits too.
I long ago gave up trying to get the standard JDK data classes to do helpful things.
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.