Can't parse string to date - java

Server return me date in format "Sat, 10 Jan 2015 07:24:00 +0100".
I try to parse this string to date, but it was unsuccessful.
This my code of parsing:
SimpleDateFormat format = new SimpleDateFormat("dd.Mm.yyyy");
try {
Date date = format.parse("Sat, 10 Jan 2015 07:24:00 +0100");
tvDate.setText(date.toString());
} catch (ParseException e) {
e.printStackTrace();
}

This is the format that you want to use:
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
Why?
The documentation goes over the symbols, but for the most part...
EEE matches a shorthand day
dd matches a two-digit date (so 01 through 31)
MMM matches a three-letter month (so Jan)
yyyy matches a four-letter year
HH:mm:ss Z is shorthand (enough) for the full 24-hour clock with Z representing the offset from GMT.

You should use a format like this if you don't care about the +0100:
SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss");
E - is day of week like "Sat"
d - day of month
M - is month
y - is year
h - is hour
m - is minute
s - is second

If you really care about the timezone, what you need to do is changing the String format of your SimpleDateFormat instance into something that represents the date String that is being returned.
Here is an example:
public static Date stringToDate(String dateString) throws ParseException {
final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
return format.parse(dateString);
}
public static void main(final String[] args) throws ParseException {
Date example = stringToDate(
"Sat, 10 Jan 2015 07:24:00 +0100");
}
You might also want to consider that SimpleDateFormat is not thread-safe and could cause unexpected behavior if not used properly. Here is a very useful explanation about this:
http://javarevisited.blogspot.com/2012/03/simpledateformat-in-java-is-not-thread.html

Related

Java unparsable date SimpleDateFormat [duplicate]

This question already has answers here:
How to get date from date time in java
(6 answers)
Why can't this SimpleDateFormat parse this date string?
(4 answers)
how to parse output of new Date().toString()
(4 answers)
Java - Unparseable date
(3 answers)
Closed 3 years ago.
I have a date that looks like that:
Sun Dec 29 00:24:09 CET 2019
I have a little utility method that parses a string date from a format to another:
public String formatDate(String date, String fromFormat, String toFormat) throws Exception {
SimpleDateFormat from = new SimpleDateFormat(fromFormat);
SimpleDateFormat to = new SimpleDateFormat(toFormat);
return to.format(from.parse(date));
}
However, with above date format, I do not find the correct date pattern to indicate to my method.
According to SimpleDateFormat patterns documentation, it should be (if I am not mistaken), the following (for Sun Dec 29 00:24:09 CET 2019):
"E M d HH:mm:ss z yyyy"
However, it throws the following exception:
java.text.ParseException: Unparseable date: "Sun Dec 29 00:24:09 CET 2019"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.aptar.simulator.Utils.formatDate(Utils.java:60)
The method is called like this:
formatDate(exDate, "E M d HH:mm:ss z yyyy", "dd-MM-yyyy HH:mm:ss");
Where
exDate = "Sun Dec 29 00:24:09 CET 2019"
Try below solution -
formatDate("Sun Dec 29 00:24:09 CET 2019","EEE MMM d HH:mm:ss z yyyy","dd-MM-yyyy HH:mm:ss");
Format should be - "EEE MMM d HH:mm:ss z yyyy"
You should use EEE for Sun and MMM for Dec
hope this helps.
Date format should be
EEE MMM dd HH:mm:ss z yyyy
Your code works fine using this format.
using java.time API
LocalDate.parse(datestr, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy")).format("TO DATE PATTERN");
Further details at Using java.time package to format date
Please find the code snippet below to solve your problem. The issue was the letter codes were correct, but there was character count mismatch , hence causing the issue. E.g.:Sun has three chars, but you were using a single E in your formatter.
public class Examp167 {
public static String formatDate(String date, String fromFormat, String toFormat) throws Exception {
SimpleDateFormat from = new SimpleDateFormat(fromFormat);
SimpleDateFormat to = new SimpleDateFormat(toFormat);
return to.format(from.parse(date));
}
public static void main(String[] args) throws Exception{
String exDate = "Sun Dec 29 00:24:09 CET 2019";
System.out.println( formatDate(exDate, "EEE MMM dd HH:mm:ss zzz yyyy", "dd-MM-yyyy HH:mm:ss"));
}
}
Firs use DateTimeFormatter instead of an old outdated class, then you should set the Locale since the day and month names are in English and last the in format needs to be MMM instead of M for the month
public static String formatDate(String date, String fromFormat, String toFormat) throws Exception {
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern(fromFormat, Locale.US);
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern(toFormat, Locale.US);
return outFormatter.format(inFormatter.parse(date));
}
Example:
String exDate = "Sun Dec 29 00:24:09 CET 2019";
String out = formatDate(exDate, "E MMM d HH:mm:ss z yyyy", "dd-MM-yyyy HH:mm:ss");
System.out.println(out);
29-12-2019 00:24:09

Date formatting is not formatting correctly

I can't figure out why this is returning
Wed Jul 02 18:21:27 CDT 2014
instead of
07/02/14 6:21 pm
pubdate = Mon, 30 Jun 2014 22:37:15 +0000
public void setPubDate(String pubDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
newFormat.format(dateFormat.parse(pubDate));
this.pubDate = date;
}
If you want to print the format you want, you have to use String to represent your date, otherwise, Date type will always print this format "dow mon dd hh:mm:ss zzz yyyy"
this.pubDate = date;//Assign the reference of date Object
//this.pubDate will have value of date NOT Format :)
But here format won't be passed to pubDate as that will remain as it is.
If you want to make your pubDate to have dd/Mm/yyyy aa format you have to format the pubDate as well here you are only assigning reference from one date to other but formation on one date won't affect the other one you have to apply that to this.pubDate whenever you want to use pubDate.
You can declare general format(Class level Object) and use it in your program whenever you want to display the date.
Because Date has toString() which per the Javadoc,
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
where:
dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
dd is the day of the month (01 through 31), as two decimal digits.
hh is the hour of the day (00 through 23), as two decimal digits.
mm is the minute within the hour (00 through 59), as two decimal digits.
ss is the second within the minute (00 through 61, as two decimal digits.
zzz is the time zone (and may reflect daylight saving time). Standard time zone
abbreviations include those recognized by the method parse. If time zone
information is not available, then zzz is empty - that is, it consists of no
characters at all.
yyyy is the year, as four decimal digits.
When you want to deviate from that, you will need your newFormat -
// As a String
System.out.println(newFormat.format(dateFormat.parse(pubDate)));
public void setPubDate(String pubDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
return newFormat.format(dateFormat.parse(pubDate));
}
Use corrected code below:
public void setPubDate(String pubDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
System.out.println("Formatted date is ="+ newFormat.format(x));
}
Try this, Create your custom date class
public class MyDate extends Date
{
#Override
public String toString() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy hh:mm aa");
return dateFormat.format(new Date());
}
}
then print the object like
System.out.println(new MyDate());

Formatting Date from Date Object with only MM/DD/YYYY

Currently using Parse to obtain a date on an object by using:
Date date = object.getCreatedAt();
The returned String when displaying it in a TextView is this:
Mon Mar 17 22:39:27 CET 2014
However I really only want the MM/DD/YYYY to display like so: 3/17/2014
I've tried this:
Date date = object.getCreatedAt();
SimpleDateFormat originalFormat = new SimpleDateFormat("MMM DDD yyyy");
try {
Date originaldate = originalFormat.parse(date.toString());
finalDate = originaldate.toString();
} catch (java.text.ParseException e1) {
e1.printStackTrace();
}
but keep getting a ParseException for "Unparseable date", any idea what's going on? If I were to simply change this line back to this:
SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM DDD HH:mm:ss z yyyy");
Then it prints out the full date again just fine with no parse exception, including all the date stuff I don't want.
Don't use parse method, use format instead :
Date date = object.getCreatedAt();
SimpleDateFormat formater = new SimpleDateFormat("M/d/yyyy");
String datestring = formater.format(date); // value is : 3/17/2014
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()
java.util.Date.toString() method always returns a String of format
dow mon dd hh:mm:ss zzz yyyy
For example, Thu Jan 10 02:00:00 EET 1992.
Your Date format "MMM DDD yyyy" expects a date String like Jan 10 1992 where 10 represents not 10th day of January but 10th day of year 1992.
Therefore to convert a date to String and convert it back to Date object using your format, you need to do
Date originaldate = originalFormat.parse(originalFormat.parse(date.toString()));
Or to convert Date.toString() to Date object,
SimpleDateFormat toStringFormat = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
Date originaldate = toStringFormat.parse(date.toString());
Lastly, if you want a Date string with format like 3/17/2014, the correct format is M/d/yyyy.
Refer to http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for help on how to write Date format.

Parsing String with spaces to Date, lead to ParseException

I have date strings in this form Thu Aug 02 00:00:00 GMT+00:00 2012
I have tried to use this method to parse these String in a Date object
public Date fromStringToDate(String data) {
Date result;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
try {
result = sdf.parse(data);
return result;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
But doesn't works and I get this error
java.text.ParseException: Unparseable date: "Thu Aug 02 00:00:00 GMT+00:00 2012"
I suppose that the problem is caused by a wrong SimpleDateFormat, but I don't know the right syntax to fix it.
You need to adjust the date format to the given string:
EEE MMM dd HH:mm:ss Z yyyy
Make sure use the correct placeholders, case sensitive, etc. Take a look to the Date and Time Patterns.
Sorry, I had a mistake with the 'z' pattern, 'Z' is:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Take a look to Locale.US, it is important to apply because the months and and days are in english.
Use this date formatting:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy")

SimpleDateFormat timezone parsing

I'm having a tough time parsing this date its the +0 at the end that is causing a problem, does anyone know whats wrong with my format string?? If I remove the +0 from the date string and the Z from the format string it works fine, unfortunately for my application that isn't an option.
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
SimpleDateFormat dateFormater = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss zZ");
try {
Date d = dateFormater.parse("Sun, 04 Dec 2011 18:40:22 GMT+0");
System.out.println(d.toLocaleString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
One approach is to use normal string-manipulation techniques to translate your string from a form that you're expecting to a form that SimpleDateFormat will understand. You haven't said exactly what range of time-zone formats are acceptable, but one possibility is something like this:
private static Date parse(String dateString) throws ParseException
{
final SimpleDateFormat dateFormat =
new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss Z");
dateString = dateString.replaceAll("(GMT[+-])(\\d)$", "$1\\0$2");
dateString = dateString.replaceAll("(GMT[+-]\\d\\d)$", "$1:00");
return dateFormat.parse(dateString);
}
That would support GMT plus-or-minus a one-or-two-digit hour offset, in addition to still supporting anything already supported by SimpleDateFormat, such as EST or GMT+1030.
Alternatively, if you know it will always be GMT, then you can just set the time-zone on the formatter, and ignore the time-zone in the string:
private static Date parse(String dateString) throws ParseException
{
final SimpleDateFormat dateFormat =
new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return dateFormat.parse(dateString);
}
You can also split the difference. I notice that the time-zone format in your string matches what's expected by TimeZone.getTimeZone(). Is that intentional? If so, you can grab that time-zone format out of the string, pass it to dateFormat.setTimeZone beforehand, and then ignore it during actual parsing:
private static Date parse(final String dateString) throws ParseException
{
final SimpleDateFormat dateFormat =
new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss");
if(dateString.indexOf("GMT") > 0)
dateFormat.setTimeZone
(
TimeZone.getTimeZone
(dateString.substring(dateString.indexOf("GMT")))
);
return dateFormat.parse(dateString);
}
If the format is that consistent, you could append 0:00 to the date string.
String dateString = "Sun, 04 Dec 2011 18:40:22 GMT+0";
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss z", Locale.ENGLISH);
Date date = sdf.parse(dateString + "0:00");
System.out.println(date);
(note that I fixed the SimpleDateFormat construction to explicitly specify the locale which would be used to parse the day of week and month names, otherwise it may fail on platforms which does not use English as default locale; I also wonder if you don't actually need HH instead of kk, but that aside)

Categories

Resources