How to parse a date?
You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
...
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
How to convert String to Date without knowing the format?
You cant!
If you have the date 2010-08-05
then it can be either 5th August 2010, or 8th May 2010 - you need to know the date format (or at least prioritise one format over the over) to tell them apart.
I need a java.time parser that can handle any valid W3C ISO 8601 date/time string
DateTimeFormatterBuilder#parseDefaulting
The examples in your link, W3C ISO 8601 are OffsetDateTime
and not ZonedDateTime
. A ZonedDateTime
require a timezone ID e.g. Europe/London
. Also, JDBC 4.2 supports OffsetDateTime
, not ZonedDateTime
.
You can use DateTimeFormatterBuilder#parseDefaulting
to parse your string into an OffsetDateTime
with default values.
Demo:
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.systemDefault();
LocalDate now = LocalDate.now(zoneId);
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("uuuu[-MM[-dd]]['T'HH[:mm[:ss[.SSSSSSSSS][.SSSSSSSS][.SSSSSSS][.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]]]][XXX]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, now.getMonthValue())
.parseDefaulting(ChronoField.DAY_OF_MONTH, now.getDayOfMonth())
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter(Locale.ENGLISH);
//Test
Stream.of(
"1997",
"1997-07",
"1997-07-16",
"1997-07-16T19:20+01:00",
"1997-07-16T19:20:30+01:00",
"1997-07-16T19:20:30.45+01:00"
).forEach(s -> System.out.println(OffsetDateTime.parse(s, dtf)));
}
}
Output:
1997-05-21T00:00Z
1997-07-21T00:00Z
1997-07-16T00:00Z
1997-07-16T19:20+01:00
1997-07-16T19:20:30+01:00
1997-07-16T19:20:30.450+01:00
The Z
in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC
timezone (which has the timezone offset of +00:00
hours).
Learn more about java.time
, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Parsing a date in Java?
You may need to use the SimpleDateFormat for parsing custom formats. This article explains the details of formatting.
"d-MMM-yyyy" corresponds to 4-Nov-2009
How do I convert date class to parse date time correctly?
Try it like this. But use the methods in the java.time package. It is superior in many ways to the java.util.Date
and supported methods which are outmoded (and quite a few are deprecated).
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
OffsetDateTime odt = OffsetDateTime.parse("1995-01-28T17:02:12.936000-0500",dtf);
DateTimeFormatter resultFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(odt.format(resultFormat));
Prints
1995-01-28 17:02:12
Related Topics
How to Capitalize the First Character of Each Word in a String
Does a Lambda Expression Create an Object on the Heap Every Time It's Executed
Quality of Image After Resize Very Low - Java
Do We Have Any Generic Function to Check If Page Has Completely Loaded in Selenium
Received Fatal Alert: Handshake_Failure Through Sslhandshakeexception
Why Is the Java Main Method Static
Regex For Splitting a String Using Space When Not Surrounded by Single or Double Quotes
Display Java.Util.Date in a Specific Format
How to Convert List≪Integer≫ to Int[] in Java
Why Does the Default Object.Tostring() Include the Hashcode
Program Not Accessing Method Paintcomponent() of Extended Jpanel Class
How to Convert Epoch to MySQL Timestamp in Java
What Are Enums and Why Are They Useful