Java String to Date, ParseException - java

I have a string named DateCompareOld, it has the value "Fri Aug 12 16:08:41 EDT 2011". I want to convert this to a date object.
SimpleDateFormat dateType = new SimpleDateFormat("E M dd H:m:s z yyyy");
Date convertDate = dateType.parse(DateCompareOld);
But everytime I try this, I get a parse exception. I have tried other SimpleDateFormat formatting criteria, but it always fails.
Suggestions?

Try this format:
EEE MMM dd HH:mm:ss zzz yyyy
Quick test:
public static void main(String[] args) throws Exception {
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
System.out.println(df.parse("Fri Aug 12 16:08:41 EDT 2011"));
}
// outputs
Fri Aug 12 15:08:41 CDT 2011
Output is in CDT, since that's where I am, but the value is right.

DateFormat dateType = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
dateType.setLenient(false);
Date convertDate = dateType.parse(DateCompareOld);

java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API*.
Another important thing to note is that your string has English text and therefore you must use Locale.ENGLISH so that you do not get an exception or some wrong result when your code is run on a JVM whose Locale is not English. Anyway, NEVER use a date-time parsing/formatting type (e.g. SimpleDateFormat, DateTimeFormatter etc.) without Locale because these types are Locale-sensitive.
Demo using modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
String strDateTime = "Fri Aug 12 16:08:41 EDT 2011";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d H:m:s z u", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2011-08-12T16:08:41-04:00[America/New_York]
If at all, you need a java.util.Date object, you can obtain it as follows:
Date date = Date.from(zdt.toInstant());
Learn more about the modern date-time API from Trail: Date Time.
Using the legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String args[]) throws ParseException {
String strDateTime = "Fri Aug 12 16:08:41 EDT 2011";
SimpleDateFormat sdf = new SimpleDateFormat("E MMM d H:m:s z y", Locale.ENGLISH);
Date date = sdf.parse(strDateTime);
// ...
}
}
Note that the java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.
* 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.

Note the String passed to SimpleDateFormat() should be corrected to "EEE MMM dd HH:mm:ss z yyyy"
Here is the code:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateTest{
public static void main(String []args){
String DateCompareOld = "Fri Aug 12 16:08:41 EDT 2011";
SimpleDateFormat dateType = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date convertDate = new Date();
try{
convertDate = dateType.parse(DateCompareOld);
}catch(ParseException pex){
pex.printStackTrace();
}
System.out.println(convertDate.toString());
}
}

Related

how to convert date from "Tue May 08 2018 13:15:00 " to "2018-05-08 13:15:00.000" in java

how to convert date from "Tue May 08 2018 13:15:00" to "2018-05-08 13:15:00.000" in java, As i have to use it for where clause in custom sql query ex- TO_timestamp('2018-05-08 13:15:00.000', 'YYYY-MM-DD HH24:MI:SS.FF')
I think I have a suggestion to try to resolve your problem...
Note: You may have to configure the Locale of the SimpleDateFormat because of the translation of dates in the String. Otherwise the exception java.text.ParseException will be thrown.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
try {
String dateStr = "Tue May 08 2018 13:15:00";
SimpleDateFormat sdfBefore = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat sdfAfter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdfBefore.parse(dateStr);
System.out.println(sdfAfter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I hope I've helped.
First you need to parse your string:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEE MMM dd uuuu H:mm:ss", Locale.ENGLISH);
String dateTimeString = "Tue May 08 2018 13:15:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime);
This prints
2018-05-08T13:15
As has been said in the comments, don’t transfer a string to your database. Assuming you are using at least Java 8 and at least JDBC 4.2 just give the parsed LocalDateTime object to the database through your PreparedStatement, for example:
PreparedStatement queryStatement = yourDbConnection.prepareStatement(
"select * from your_table where your_column = ?");
queryStatement.setObject(1, dateTime);
I am assuming that the source of your string and your database agree about in which time zone the date and time should be interpreted. For most purposes you should prefer to be explicit about time zone.
For anyone reading along and needing a string like 2018-05-08 13:15:00.000 for some other purpose than a database query, the way to obtain this format is through one more formatter:
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String formattedDateTimeString = dateTime.format(targetFormatter);
System.out.println(formattedDateTimeString);
This prints
2018-05-08 13:15:00.000
Link: The Java™ Tutorials: Trail: Date Time explaining how to use java.time, the modern Java date and time API.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
String dateStr = "Tue May 08 2018 13:15:00";
DateTimeFormatter formatterFrom = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss");
LocalDateTime localDate = LocalDateTime.parse(dateStr, formatterFrom);
DateTimeFormatter formatterTo = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String localDate1 = formatterTo.format(localDate);
System.out.println(localDate1); // 2018-05-08 13:15:00.000
}
}

Different values when parsing date [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
I am trying to parse this date with SimpleDateFormat and it is not working:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formaterclass {
public static void main(String[] args) throws ParseException{
String strDate = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dateStr = formatter.parse(strDate);
String formattedDate = formatter.format(dateStr);
System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
Date date1 = formatter.parse(formattedDate);
formatter = new SimpleDateFormat("dd-MMM-yyyy");
formattedDate = formatter.format(date1);
System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
}
}
If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?
PS. I got this date from a jDatePicker and there is no instruction on how modify the date format I get when the user chooses 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
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
We now have a more modern way to do this work.
java.time
The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.
Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.
By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.
String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );
Dump to console.
System.out.println ( "zdt : " + zdt );
When run.
zdt : 2009-06-18T20:56:02-04:00[America/New_York]
Adjust Time Zone
For fun let's adjust to the India time zone.
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]
Convert to j.u.Date
If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
In response to:
"How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate
Try this:
With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.
public static void main(String[] args) throws ParseException {
String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
Date f = new Date(fecha);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
fecha = sdf.format(f);
System.out.println(fecha);
}

Error parsing date string

I need to parse this string as a date:
Mon Jun 10 00:00:00 CEST 2013
Here is what I do:
SimpleDateFormat sdf = new SimpleDateFormat("ccc MMM dd HH:mm:ss z yyyy");
Date date = sdf.parse(dateString);
But I get a ParseException:
Unparseable date: "Wed Oct 02 00:00:00 CEST 2013" (at offset 0)
Any help please?
As others have said, you need EEE instead of ccc - but you should also specify a locale, so that it doesn't try to parse the month and day names (and other things) using your system default locale:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy",
Locale.US);
Your format is wrong. You need to use EEE instead of ccc, where E means Day name in week.
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Have a look at the docs regarding all the valid patterns available for SimpleDateFormat.
Replace ccc with EEE in the pattern to specify the day of the week:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Example: https://gist.github.com/kmb385/8781482
Update the format as below :
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
It is a Locale problem. That's because dates are represented differently between Locales, so the JVM fires an exception if the Date is not in the correct format. You can solve it by setting a custom Locale:
String str = "Mon Jun 10 00:00:00 EST 2013";
Locale.setDefault(Locale.US);
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = sdf.parse(str);
System.out.println(date);
IDEone examples do work because the default locale is Locale.US
java.time
The accepted answer uses SimpleDateFormat which was the correct thing to do in Feb 2014. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern Date-Time API. Since then, it is highly recommended to stop using the legacy date-time API.
Note: Never use date-time formatting/parsing API without a Locale.
Solution using the modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String stdDateTime = "Mon Jun 10 00:00:00 CEST 2013";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(stdDateTime, parser);
System.out.println(zdt);
}
}
Output:
2013-06-10T00:00+02:00[Europe/Paris]
If for any reason, you need an instance of java.util.Date, you can get it as follow:
Date date = Date.from(zdt.toInstant());
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.

Extract date from String java

I have a String with several dates, for example:
[20-Jul-2012 5:11:36,670 UTC PM, 20-Jul-2012 5:11:36,683 UTC PM]
How do I read this string and extract each date? I'm using the SimpleDateFormat class to create a regex.
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");
I've tried :
I've just did, to get the first one and it changes the format and the timezone:
ParsePosition parsePos = new ParsePosition(1);
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");
System.out.println(format2.parse(entry.getValue().toString(), parsePos)) ;
Output : Fri Jul 20 06:11:36 BST 2012
You can try:
parsePos = new ParsePosition(1);
while((date = format2.parse(yourString, parsePos)!=null){
//use date
}
java.time
The question uses SimpleDateFormat which was the correct thing to do in 2012. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern Date-Time API. Since then, it is strongly recommended to stop using the legacy date-time API.
Solution using the modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("d-MMM-uuuu h:m:s,SSS VV a", Locale.ENGLISH);
Stream.of(
"20-Jul-2012 5:11:36,670 UTC PM",
"20-Jul-2012 5:11:36,683 UTC PM"
)
.map(s -> ZonedDateTime.parse(s, parser))
.forEach(System.out::println);
}
}
Output:
2012-07-20T17:11:36.670Z[UTC]
2012-07-20T17:11:36.683Z[UTC]
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.

Unparseable date exception in java

These lines of codes
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
ContentValues values = new ContentValues();
values.put(COL_EVENT_ID, appointment.mEventId);
try {
values.put(COL_START_DATE, String.valueOf(formatter.parse(appointment.mStartDate.toString())));
values.put(COL_END_DATE, String.valueOf(formatter.parse(appointment.mEndDate.toString())));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
causees this exception
10-15 11:44:38.150: WARN/System.err(3861): java.text.ParseException: Unparseable date: "Mon Jan 10 00:10:00 GMT+02:00 2011"
what is the possible solution ?
Your format is completely wrong. Not only are you using mm (which means minutes) when you probably meant MM, but this:
Mon Jan 10 00:10:00 GMT+02:00 2011
is clearly not in the format
dd/MM/yy
You probably want something like
EEE MMM dd HH:mm:ss z yyyy
EDIT: That works for me in desktop Java:
import java.text.*;
public class Test {
public static void main(String[] args) throws ParseException {
String value = "Mon Jan 10 00:10:00 GMT+02:00 2011";
String pattern = "EEE MMM dd HH:mm:ss z yyyy";
DateFormat format = new SimpleDateFormat(pattern);
System.out.println(format.parse(value));
}
}
You may want to set the culture of the SimpleDateFormat of course.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Mon Jan 10 00:10:00 GMT+02:00 2011";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d H:m:s OOOO uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
ONLINE DEMO
Notes:
m specifies minute-of-hour whereas M specifies month-of-year. You have wrongly used the former.
The pattern used with the parser (DateTimeFormatter or SimpleDateFormat) should match the input date-time string. Your pattern, dd/mm/yy is off by far.
Never use SimpleDateFormat or DateTimeFormatter without a Locale.
Learn more about 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.

Categories

Resources