SimpleDateFormat timezone parsing - java

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)

Related

How to convert Date to a particular format in android?

"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);
Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.
This is modified code that you should use:
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);
Use hh for hours in order to get correct time.
Java 8 and later
Java 8 introduced new classes for time manipulation, so use following code in such cases:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));
Use h for hour format, since in this case hour has only one digit.
conversion from string to date and date to string
String deliveryDate="2018-09-04";
SimpleDateFormat dateFormatprev = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormatprev.parse(deliveryDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy");
String changedDate = dateFormat.format(d);
You can use following method for this problem. We simply need to pass Current date format, required date format and Date String.
private String changeDateFormat(String currentFormat,String requiredFormat,String dateString){
String result="";
if (Strings.isNullOrEmpty(dateString)){
return result;
}
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date=null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}
This method will return Date String in format you require.
In your case method call will be:
String date = changeDateFormat("MMM dd, yyyy hh:mm:ss a","dd MMM yyyy","Mar 10, 2016 6:30:00 PM");
You should parse() the String into Date and then format it into the desired format. You can use MMM dd, yyyy HH:mm:ss a format to parse the given String.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String date = "Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Date newDate = spf.parse(date);
spf = new SimpleDateFormat("dd MMM yyyy");
String newDateString = spf.format(newDate);
System.out.println(newDateString);
}
Output:
10 Mar 2016
For the sake of completeness, here is the modern version. This is for anyone reading this who either uses Java 8 or later or is happy with a (good and futureproof) external library.
String date = "Mar 10, 2016 6:30:00 PM";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter newFormatter
= DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);
date = LocalDateTime.parse(date, parseFormatter).format(newFormatter);
System.out.println(date);
This prints the desired
10 Mar 2016
Please note the use of explicit locale for both DateTimeFormatter objects. “Mar” and “PM” both are in English, so neither the parsing nor the formatting will work unless some English-speaking locale is used. By giving it explicitly we are making the code robust enough to behave as expected also on computers and JVMs with other default locales.
To use the above on Android, use ThreeTenABP, please see How to use ThreeTenABP in Android Project. On other Java 6 and 7 use ThreeTen Backport.
You need to use SimpleDateFormat class to do the needful for you
String date = "Your input date"
DateFormat originalFormat = new SimpleDateFormat("<Your Input format here>", Locale.US)
DateFormat targetFormat = new SimpleDateFormat("<Your desired format here>", Locale.US)
Date Fdate = originalFormat.parse(date)
formattedDate = targetFormat.format(Fdate)
public static String formatDate(String fromFormat, String toFormat, String dateToFormat) {
SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat);
Date date = null;
try {
date = inFormat.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outFormat = new SimpleDateFormat(toFormat);
return outFormat.format(date);
}
Use:
formatDate("dd-MM-yyyy", "EEEE, dd MMMM yyyy","26-07-2019");
Result:
Friday, 26 July 2019

Can't parse string to date

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

Convert string to a particular date format

I have a date in the format:Thu- Mar 22 2012.Its is obtained in a string variable date1.I need to convert the date in string variable to date format.I tried the below ccode but failed to parse the date;Please help.
DateFormat formatter;
Date formatted_date= null;
formatter = new SimpleDateFormat("EEE-MM d yyyy");
try {
formatted_date= (Date) formatter.parse(date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You need three Ms 'MMM' to parse a months abbreviation like 'Mar'. And please check the whitespace after 'EEE-'.
Change it to following format
EEE- MMM d yyyy
Note space after - and MMM
Thu- Mar 22 2012
EEE- MMM dd yyyy
I think you need something like this
UPD: for date formatting:
SimpleDateFormat toStringFormatter = new SimpleDateFormat("EEE MMM dd yyyy");
String formattedDate = toStringFormatter.format(date);
so parse() is for String -> Date, and format() is for Date -> String
If the already posted answers doesn't work then you surely have a problem with the locale. Try the following SimpleDateFormat:
formatter = new SimpleDateFormat("EEE- MMM d yyyy", Locale.ENGLISH);
I thank With the given mode and given the locale's default date format symbols constructor SimpleDateFormat. Note: This constructor may not support all locales. To cover all the language environment
public SimpleDateFormat(String pattern,Locale locale)
//local:Locale.ENGLISH
//default is not English
formatter = new SimpleDateFormat("EEE, MMM d, ''yy", Locale.ENGLISH);
try {
formatted_date= (Date) formatter.parse("Wed, Jul 4, '01");
} catch (ParseException e) {
e.printStackTrace();
}

java string to utc date

This question is a duplicate of this question by intention. It seems like the older one is "ignored", while none of the answers there is the answer.
I need to parse a given date with a given date pattern/format.
I have this code, which is supposed to work:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main
{
public static void main(String[] args)
{
final Date date = string_to_date("EEE MMM dd HH:mm:ss zzz yyyy",
"Thu Aug 14 16:45:37 UTC 2011");
System.out.println(date);
}
private static Date string_to_date(final String date_format,
final String textual_date)
{
Date ret = null;
final SimpleDateFormat date_formatter = new SimpleDateFormat(
date_format);
try
{
ret = date_formatter.parse(textual_date);
}
catch (ParseException e)
{
e.printStackTrace();
}
return ret;
}
}
For some reason I'm getting this output:
java.text.ParseException: Unparseable date: "Thu Aug 14 16:45:37 UTC 2011"
at java.text.DateFormat.parse(DateFormat.java:337)
at Main.string_to_date(Main.java:24)
at Main.main(Main.java:10)
null
What's wrong with my date pattern? This seems to be a mystery.
Your platform default locale is apparently not English. Thu and Aug are English. You need to explicitly specify the Locale as 2nd argument in the constructor of SimpleDateFormat:
final SimpleDateFormat date_formatter =
new SimpleDateFormat(date_format, Locale.ENGLISH); // <--- Look, with locale.
Without it, the platform default locale will be used instead to parse day/month names. You can learn about your platform default locale by Locale#getDefault() the following way:
System.out.println(Locale.getDefault());
This should parse the given string.
public static void main(String[] args) throws ParseException
{
String sd = "Thu Aug 14 16:45:37 UTC 2011";
String dp = "EEE MMM dd HH:mm:ss zzz yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dp);
Date d = sdf.parse(sd);
System.out.println(d);
}
I should have specify a locale, like this:
final SimpleDateFormat date_formatter = new SimpleDateFormat(date_format, Locale.ENGLISH);
Thanks to BalusC with his great answer!

Twitter date unparseable?

I want to convert the date string in a Twitter response to a Date object, but I always get a ParseException and I cannot see the error!?!
Input string: Thu Dec 23 18:26:07 +0000 2010
SimpleDateFormat Pattern:
EEE MMM dd HH:mm:ss ZZZZZ yyyy
Method:
public static Date getTwitterDate(String date) {
SimpleDateFormat sf = new SimpleDateFormat(TWITTER);
sf.setLenient(true);
Date twitterDate = null;
try {
twitterDate = sf.parse(date);
} catch (Exception e) {}
return twitterDate;
}
I also tried this: http://friendpaste.com/2IaKdlT3Zat4ANwdAhxAmZ but that gives the same result.
I use Java 1.6 on Mac OS X.
Cheers,
Andi
Your format string works for me, see:
public static Date getTwitterDate(String date) throws ParseException {
final String TWITTER="EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(TWITTER);
sf.setLenient(true);
return sf.parse(date);
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(getTwitterDate("Thu Dec 3 18:26:07 +0000 2010"));
}
Output:
Fri Dec 03 18:26:07 GMT 2010
UPDATE
Roland Illig is right: SimpleDateFormat is Locale dependent, so
just use an explicit english Locale:
SimpleDateFormat sf = new SimpleDateFormat(TWITTER,Locale.ENGLISH);
This works for me ;)
public static Date getTwitterDate(String date) throws ParseException
{
final String TWITTER = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat sf = new SimpleDateFormat(TWITTER, Locale.ENGLISH);
sf.setLenient(true);
return sf.parse(date);
}
Maybe you are in a locale where ‘Tue‘ is not a recognized day of week, for example German. Try to use the ‘SimpleDateFormat‘ constructor that accepts a ‘Locale‘ as a parameter, and pass it ‘Locale.ROOT‘.
You should not have ZZZZZ but only Z for the timezone.
See samples in http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html for more information.
EEE, d MMM yyyy HH:mm:ss Z > Wed, 4 Jul 2001 12:08:56 -0700
SimpleDateFormat is not thread safe. "EEE MMM dd HH:mm:ss ZZZZZ yyyy" was working in our application, but failing in a small percentage of cases. We finally realized that the issue was coming from multiple threads using the same instance of SimpleDateFormat.
Here is one workaround: http://www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html
Function for convert Twitter Date :
String old_date="Thu Jul 05 22:15:04 GMT+05:30 2012";
private String Convert_Twitter_Date(String old_date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
SimpleDateFormat old = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy",Locale.ENGLISH);
old.setLenient(true);
Date date = null;
try {
date = old.parse(old_date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sdf.format(date);
}
The output format like : 05-Jul-2012 11:54:30

Categories

Resources