Java: unparseable date exception - java

While trying to transform the date format I get an exception:unparseable date and don't know how to fix this problem.
I am receiving a string which represents an event date and would like to display this date in different format in GUI.
What I was trying to do is the following:
private String modifyDateLayout(String inputDate){
try {
//inputDate = "2010-01-04 01:32:27 UTC";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
} catch (ParseException e) {
e.printStackTrace();
return "15.01.2010";
}
}
Anyway the line
String modifiedDateString = originalDate.toString();
is dummy. I would like to get a date string in the following format:
dd.MM.yyyy HH:mm:ss
and the input String example is the following:
2010-01-04 01:32:27 UTC
Does anyone know how to convert the example date (String) above into a String format dd.MM.yyyy HH:mm:ss?
Thank you!
Edit: I fixed the wrong input date format but still it doesn't work. Above is the pasted method and below is the screen image from debugging session.
alt text http://img683.imageshack.us/img683/193/dateproblem.png
#Update
I ran
String[] timezones = TimeZone.getAvailableIDs();
and there is UTC String in the array. It's a strange problem.
I did a dirty hack that works:
private String modifyDateLayout(String inputDate){
try {
inputDate = inputDate.replace(" UTC", "");
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
} catch (ParseException e) {
e.printStackTrace();
return "15.01.2010";
}
}
But still I would prefer to transform the original input without cutting timezone away.
This code is written for Android phone using JDK 1.6.

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().
private String modifyDateLayout(String inputDate) throws ParseException{
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.
Update: Okay, I did a test:
public static void main(String[] args) throws Exception {
String inputDate = "2010-01-04 01:32:27 UTC";
String newDate = new Test().modifyDateLayout(inputDate);
System.out.println(newDate);
}
This correctly prints:
03.01.2010 21:32:27
(I'm on GMT-4)
Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.
This from the accepted answer helped me solve this problem:
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern
The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema
I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:
String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);
Next step is parse stringDate to Date:
Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);
Note that, parse method throws ParseException

Related

String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]

This question already has answers here:
Java Date Error
(8 answers)
Closed 4 years ago.
I want to convert String values in the format of mm/dd/yy to YYYY-MM-DD Date. how to do this conversion?
The input parameter is: 03/01/18
Code to convert String to Date is given below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When tried to convert using this method it shows the following error
java.text.ParseException: Unparseable date: "03/01/18"
As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.
To Convert as Date,
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);
To Print it out in the other format,
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)
You are writing it the wrong way. In fact, for the date you want to convert, you need to write
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
The format you are passing to SimpleDateFormat is ("yyyy-MM-dd") which expects date to be in form 2013-03-01 and hence the error.
You need to supply the correct format that you are passing your input as something like below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
The solution for the above problem
Convert the String date value in the Format of "dd/mm/yy" to Date.
By using the converted Date can able to frame the required date format.
The method has given below
public static String stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
String dateString = null;
try {
// convert to Date Format From "dd/mm/yy" to Date
date = formatter.parse(dateVlaue);
// from the Converted date to the required format eg : "yyyy-MM-dd"
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.
public static Optional<LocalDate> stringToDateLinen(String dateValue) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
try {
return Optional.of(LocalDate.parse(dateValue, dateFormatter));
} catch (DateTimeParseException dtpe) {
return Optional.empty();
}
}
Try it:
stringToDateLinen("03/01/18")
.ifPresentOrElse(System.out::println,
() -> System.out.println("Could not parse"));
Output:
2018-01-03
I recommend you stay away from SimpleDateFormat. It is long outdated and notoriously troublesome too. And Date is just as outdated. Instead use LocalDate and DateTimeFormatter from java.time, the modern Java date and time API. It is so much nicer to work with. A LocalDate is a date without time of day, so this suites your requirements much more nicely than a Date, which despite its name is a point in time. LocalDate.toString() produces exactly the format you said you desired (though the LocalDate doesn’t have a format in it).
My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.
What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null is a NullPointerException waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError if the situation is not supposed to happen. In my code I am returning an Optional, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException. In the code calling the method I am using the ifPresentOrElse method introduced in Java 9. If not using Java 9 yet, use ifPresent and/or read more about using Optional elsewhere.
What went wrong in your code?
The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.
Link
Oracle tutorial: Date Time explaining how to use java.time.

joda time parse method return format

I have very simple question - I read couple of threads here but I still do not understand how to get simple thing. I want to send string to method and get back joda date. I had no problem to build it up, but return format is 2015-03-11T17:13:09:000+01:00. How can I get desired (e.g. mmm-dd hh:mm) format back from below mentioned method (it mustto be a dateTime for sorting purposes on FX form)? I tried to gamble with another dateTimeFormatter but had no luck. Thank you very much in advance
public static DateTime stringToDateTime(String textDate) throws ParseException
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
DateTime jodaTime = dateTimeFormatter.parseDateTime(textDate);
return jodaTime;
}
What do you mean by "return format"? "Format" term here could only be related to a string representation of a DateTime object. That means you should specify format of your input string (what you've already done in your code) - and a corresponding DateTime object will be created. After that you probably use toString() to check the results, but DateTime.toString() uses ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ) according to JavaDoc - that gives you your 2015-03-11T17:13:09:000+01:00 result.
So to get it as desired you could try using toString(String pattern) method with format you need. But once again - it's just an output format to convert DateTime to String, it doesn't affect the datetime stored in your DateTime object.
I just use Calendar object so this is a possible way to do it:
static String stringToDateTime(String textDate) {
Calendar c = new GregorianCalendar();
// How you want the input to be formatted
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = df.parse(textDate);
c.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
// How do you want to print your date
df= new SimpleDateFormat("dd-MM-yy");
return df.format(c.getTime());
}
// input
String myDate = "2015-04-15 14:25:25";
System.out.println(stringToDateTime(myDate));

How to converted timestamp string to a date in java

I have a string "1427241600000" and I want it converted to "yyyy-MM-dd" format.
I have tried, but I am not able to parse it, please review the below code
try {
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date =sf.parse(str);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
I would like to know where I went wrong.
You should try it the other way around. First get the Date out of the milliTime and then format it.
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(Long.parseLong(str));
System.out.println(sf.format(date));
the conversion is highly dependent on what format the timestamp is in. But i assume the whole thing should actually be a long and is simply the systemtime from when the timestamp was created. So this should work:
String str = ...;
Date date = new Date(Long.parseLong(str));
Use Date date =new Date(Long.parseLong(str)); to convert your String to Date object.
if you are using SimpleDateFormat() the format specified as a parameter to this function should match the format of the date in the String (str in your case). In your case yyyy-MM-dd does not match the format of the time stamp (1427241600000).
You can do it like this:
use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

Why java SimpleDateFormat can parse formatted text with extra characters?

I am parsing date strings from user input with MM-dd-yyyy HH:mm:ss format, and I found 12-20-2012 10:10:10 abcdexxxx could be pasred as well. How can this happen? Here is my code:
SimpleDateFormat df = new SimpleDateFormat( "MM-dd-yyyy HH:mm:ss" );
String currColValue = "12-20-2012 10:10:10 abcdexxxx";
try{
d=df.parse( currColValue );
}catch( ParseException e ){
System.out.println("Error parsing date: "+e.getMessage());
}
But there is no exception, the String value is parsed to be a Date. Why?
Per the Javadoc of the parse method:
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
(emphases mine).
Contrary to the implication of comments above, this has nothing to do with lenient parsing; rather, it's just that this method is not intended to consume the whole string. If you wish to validate that it consumed the whole string, I suppose you could set up a ParsePosition object and use the two-arg overload, and then examine the ParsePosition afterward to see if it parsed to the end of the string.
java.time
I should like to contribute the modern answer. This question was asked just the month before java.time, the modern Java date and time API, came out, which we all should be using now.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss");
String currColValue = "12-20-2012 10:10:10 abcdexxxx";
try {
LocalDateTime ldt = LocalDateTime.parse(currColValue, formatter);
// Do something with ldt
} catch (DateTimeParseException e) {
System.out.println("Error parsing date and time: " + e.getMessage());
}
Output:
Error parsing date and time: Text '12-20-2012 10:10:10 abcdexxxx' could not be parsed, unparsed text found at index 19
Contrary to the old SimpleDateFormat class the parse methods of the modern classes do insist on parsing the entire string (there is a way to parse only part of the string if that is what you require). Also please note the precision and clarity of the exception message. By the way, SimpleDateFormat is not only long outdated, it is also notoriously troublesome. You found just one of many surprising problems it has. I recommend that you no longer use SimpleDateFormat and Date.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Check SimpleDateFormat.parse(String) doc. It clearly says it.
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#parse(java.lang.String)
I want to contibute to the above correct answers with examples, using the method overload
public Date parse(String text, ParsePosition pos);
To parse the exact whole string just create a new ParsePosition object (with index 0, indicating that parse needs to start from begin), pass it to the method, and inspect its index property after parse.
Index is where the parse did end. If matches with string length then the string matches exactly form start to end.
Here is a unit test demonstrating it
public class DateParseUnitTest {
#Test
public void testParse(){
Date goodDate = parseExact("2019-11-05");
Date badDate1 = parseExact("foo 2019-11-05");
Date badDate2 = parseExact("2019-11-05 foo");
assert(goodDate != null);
assert(badDate1 == null);
assert(badDate2 == null);
}
#Nullable
private Date parseExact(#NonNull String text){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(text, pos);
if (pos.getIndex() != text.length())
return null;
return date;
}
}

Date conversion in Java

How can I take a string in a format such as: 2008-06-02 00:00:00.0 and convert it to: 02-Jun-2008?
Can I somehow take the original string, convert it to a Date object, then use a formatter to get the final output (rather than parsing the string myself)? Thanks!
You can use SimpleDateFormat to convert between a String and a Date object and vice versa based on a pattern. Click the API link, you'll see patterns being explained in detail. A 4-digit year can be represented with yyyy, a 3-character month abbreviation can be represented with MMM and so on.
First you need to parse the String of the first format into a Date object:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf1.parse(inputString);
Then you need to format the Date into a String of the second format:
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String outputString = sdf2.format(date);
Note that you need to take the Locale into account as well to get the month to be printed in English, else it will use the platform's default locale to translate the month.
Use 2 instances of SimpleDateFormat class. One for converting your input string to date and second to convert date back to string but in another format.
Here is an example of using SimpleDateFormat.
DateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
DateFormat endFormat = new SimpleDateFormat("dd-MM-yyyy");
String outputString = null;
try {
Date date = startFormat.parse(inputString);
outputString = endFormat.format(date);
} catch(ParseException pe) {
throw new IllegalArgumentException(inputString + " is not properly formated.", pe);
}
You can definitely use SimpleDateFormat class like others have recommended.
Another suggestion if it applies in your case. If you are getting this data from a sql query you can also use to_char() method to format it in the query itself. For example: to_char(column_name,'DD-MON-YYYY')

Categories