simpleDateFormat throws unparseable date exception - android

I have been trying to parse a string to a Date and i have searched this everywhere and could not find a solution to it. I have a String formatted. And when I try to parse it it always throws an exception though i have tried setting Locale.English also and giving the date pattern (obviously).
And my Date pattern is "Wed, 29 Jun 2016 16:16:32 +0000". Thanks in advance for help.
dateFormat = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss 'Z'", Locale.ENGLISH);
try {
String dateA = "Wed, 29 Jun 2016 16:16:32 +0000";
String dateB = "Wed, 29 Jun 2016 16:04:54 +0000";
Date parsedDateA = dateFormat.parse(dateA);
Date parsedDateB = dateFormat.parse(dateB);
if (parsedDateA .equals(parsedDateB ) || parsedDateA .before(parsedDateB )) {
//Do some work here
}
} catch (ParseException e) {
e.printStackTrace();
}

From the docs : "EEE, d MMM yyyy HH:mm:ss Z" . The 'd' should be lowercase.
Uppercase D represents the day in year rather than day of the month.
Edit:
Thanks to #MikeM.'s suggestion: remove the single quotes 'Z' you have around Z. I did not notice that at first.

Related

Cannot convert String date into Date - Unparseable date error

I have date String in the following format - eg.:
Thu, 17 Mar 2016 19:30:25 +0000
Sun, 06 Mar 2016 12:43:13 +0000
I want to convert this date into a more readable format:
Thu, 17 Mar 2016
Sun, 06 Mar 2016
public static String getMoreReadableDateFormat(String dateStringToConvert) {
SimpleDateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Date convertedDate;
try {
convertedDate = dateFormat.parse(dateStringToConvert);
} catch (ParseException e) {
// could not convert date, return the initial form
return dateStringToConvert;
}
String formattedDate = new SimpleDateFormat("E, dd MMM yyyy").format(convertedDate);
return formattedDate;
}
Strange is that this code works fine for me (I get the simplified date version), but for some other peoples from other countries is not working and cannot convert date string into the simplified version. I know it has to be related to Locale, but don't know how to fix this.
You can try to set your phone's date format to french, or something else to reproduce the behavior you mentioned.
Are you sure that dateStringToConvert parameter is always in a correct format ?
I would suggest you change the first line to:
SimpleDateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
It's important to note here the difference between DateFormats like Date, Time, and Date and Time as listed in the link below. Given your block of code, it looks like you expect a Date and Time string to be passed in and you expect to return just a Date. I'm guessing that it's not following the format that you declare as
new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z")
Also, it doesn't look like that string matches the Predefined Formats. You can try reformatting it to use
DateFormat dateAndTimeFormatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, currentLocale);
This would accept a string like
"Tuesday, June 30, 2009 7:03:47 AM PDT"
parse the parameter using the formatter above and then convert a different dateFormatter
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale);
you can get the default local from
Locale.getDefault()
So your code would look something like this
public static String convertDate(String dateStringToConvert) throws ParseException {
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.getDefault());
Date convertedDate = dateFormat.parse(dateStringToConvert);
return DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault()).format(convertedDate);
}
Check here for more information related to using predefined formats.
https://docs.oracle.com/javase/tutorial/i18n/format/dateFormat.html

How to convert Thu Dec 17 15:37:43 GMT+05:30 2015 string to Date in android

SimpleDateFormat format =new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
format.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
try {
long diff2=format.parse(accidentReports.getAccidentDate());
}
getting this output :: Thu Dec 17 15:37:43 GMT+05:30 5
If you required Date Object form String use:
Date date=null;
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
String temp = "Thu Dec 17 15:37:43 GMT+05:30 2015";
try {
date = formatter.parse(temp);
Log.e("formated date ", date + "");
} catch (ParseException e) {
e.printStackTrace();
}
Your OutPut is
Thu Dec 17 15:37:43 GMT+05:30 2015:
in Date Object
For Again Convert it to String:
String formateDate = new SimpleDateFormat("MM-dd-yyyy").format(date);
Log.v("output date ",formateDate);
Now your output is:
12-17-2015
In Kotlin,
private fun convertToCustomFormat(dateStr: String?): String {
val utc = TimeZone.getTimeZone("UTC")
val sourceFormat = SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")
val destFormat = SimpleDateFormat("dd-MMM-YYYY HH:mm aa")
sourceFormat.timeZone = utc
val convertedDate = sourceFormat.parse(dateStr)
return destFormat.format(convertedDate)
}
Input Date :
Sat Dec 19 12:50:57 GMT+05:30 2020
Output Date Format :
19-Dec-2020 12:50 PM
Explanation :
Format Explanation
EEE : Day ( Mon )
MMM : Month in words ( Dec )
MM : Day in Count ( 324 )
mm : Month ( 12 )
dd : Date ( 3 )
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
aa : ( AM / PM )
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* .
Using modern date-time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Thu Dec 17 15:37:43 GMT+05:30 2015";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("E MMM d H:m:s O u", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtfInput);
// Default string i.e. OffsetDateTime#toString
System.out.println(odt);
// A custom string
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssO", Locale.ENGLISH);
String formatted = odt.format(dtfOutput);
System.out.println(formatted);
}
}
Output:
2015-12-17T15:37:43+05:30
2015-12-17T15:37:43GMT+5:30
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.
Please check my solution i have used before:
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
try {
String temp = "Thu Dec 17 15:37:43 GMT+05:30 2015";
Date expiry = formatter.parse(temp);
} catch (Exception e) {
e.printStackTrace();
}
Sorry this may be late to answer, but it may help to anyone in near future.
just call this simple method while passing your date (Thu Dec 17 15:37:43 GMT+05:30 2015) and you will get result like this : 2015-12-17
private String getFormattedDate(Date timeZone){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(timeZone);
return formattedDate;
}
Just keep in mind, this is a Date formatted value not a String value.
how to call :
getFormattedDate(date);

Simple date formatting giving wrong time

I am trying to parse a String to a Date and it giving me right date where as time is wrong.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm aaa");
try {
Date date = formatter.parse("2015-08-20 05:00 AM");
Log.e("date", date+""); // Logcat printing Thu Aug 20 00:00:00 GMT+05:30 2015
} catch (ParseException e) {
Log.e("Error",e.toString());
}
As you can see irrespective of the time every time parsed date time showing 00:00:00
What I want is Thu Aug 20 05:00:00 GMT+05:30 2015
It seems the problem was that your pattern String specified am/pm, but was using uppercase H's for the hour characters. These indicate a 24-hour clock, which obviously doesn't use am/pm. Change the hour characters to lowercase h's, which indicate the hour in am/pm (0-11).
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aaa");
The docs for SimpleDateFormat explain the various acceptable pattern characters.
Try below code
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy hh:mm:ss z");
String dateToStr = format.format(new Date());
System.out.println("dateToStr=>" + dateToStr);
try {
Date strToDate = format.parse(dateToStr);
System.out.println("strToDate=>" + strToDate);
} catch (ParseException e) {
e.printStackTrace();
}
Maybe its related to time zone issues, at what time zone is your input?, i'd suggest to make sure your paramater is on UTC timezone and then using formatter like this :
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm aaa");
formatter .setTimeZone(TimeZone.getTimeZone("UTC"));
Try this code you missed some lines of code
SimpleDateFormat mFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aa", Locale.getDefault());
mFormatter.setTimeZone(TimeZone.getTimeZone("India"));
Date startDate = mFormatter.parse("2015-08-20 05:00 AM");
This code working fine for me.

"Fri, 12 Sep 2014 05:00:23 GMT",what's wrong with SimpleDateFormat?

"Fri, 12 Sep 2014 05:00:23 GMT",what's wrong with SimpleDateFormat?
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.parse(dateString);
format: "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
dateString:"Fri, 12 Sep 2014 05:00:23 GMT"
what's wrong ?
Assuming your problem is that the date is coming out wrong, the SimpleDateFormat conversion specifier for timezone is z rather than 'GMT' (although you can use Z and X for the other two variants, RFC822 and ISO8601 respectively).
With your specifier, I get a local time of 5am. If I use the correct specifier in my code, it works fine:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main (String[] args) {
String format = "EEE, dd MMM yyyy HH:mm:ss z";
String date = "Fri, 12 Sep 2014 05:00:23 GMT";
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date dt = sdf.parse(date);
System.out.println(dt);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output of that program (for Perth, Western Australia, which is UTC+8) is, as expected:
Fri Sep 12 13:00:23 WST 2014
See the SimpleDateFormat online documentation for more detail.
If you still have troubles, try removing the individual items from your format and date strings until it starts working. Once you've established the problematic format specifier, it will be easier to track down.
Use "z" in your pattern because GMT is not just a literal but has to be interpreted as timezone offset UTC+00:00. And set the locale to English because you have english abbreviations of day-of-week and month:
String format = "EEE, dd MMM yyyy HH:mm:ss z";
String date = "Fri, 12 Sep 2014 05:00:23 GMT";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);

Unparseable date Exception

Well, i'm trying to catch date from rss, and i get this execption in logcat:
E/AndroidNews( 870): Caused by: java.text.ParseException: Unparseable date: "Su
n, 02 Oct 2011 14:00:00 +0100"
E/AndroidNews( 870): at java.text.DateFormat.parse(DateFormat.java:626)
E/AndroidNews( 870): at com.warriorpoint.androidxmlsimple.Message.setDate(Mes
sage.java:57)
My formatter is
static SimpleDateFormat FORMATTER =
new SimpleDateFormat("yyyy-MM-dd HH:mm");´
My method setDate();
public void setDate(String date) {
this.date=null;
// pad the date if necessary
while (!date.endsWith("00")){
date += "0";
}
try {
this.date = FORMATTER.parse(date.trim());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
You're using the wrong format, for "Sun, 02 Oct 2011 14:00:00 +0100" try this instead:
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US)
This also forces the locale to (American) English, so the day and month names aren't affected by the device's locale, e.g. expecting "Dom" for "Sun" and "Oct" for "Out" in a Portuguese locale (I peeked at your profile).
The format you have in your question would only be able to parse dates like "2011-10-02 14:00".
Also, don't pad the date, let your formatter do the parsing.
If you want to output/display a java.util.Date in a certain way, just create a new SimpleDateFormat (let's call it displayFmt) with the desired formatting string and call format() on it:
String formattedDate = new SimpleDateFormat("dd MM yyyy H").format(date);
This will give you something like "02 10 2011 17" for today, formatted in the user's/device's preferred locale.
Please note that in your comment, you said dd mm yyyy h (lower case m and h) which would give you "dayOfMonth minutes year hours12" -- I think that's not what you want, so I changed it to an upper case M and upper case H to give you "dayOfMonth month year hours24".

Categories

Resources