I need to change the input date format to my desired format.
String time = "Fri, 02 Nov 2012 11:58 pm CET";
SimpleDateFormat displayFormat =
new SimpleDateFormat("dd.MM.yyyy, HH:mm");
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm aa z");
Date date = parseFormat.parse(time);
System.out.println("output is " + displayFormat.format(date));
it gives me this error
java.text.ParseException: Unparseable date: "Fri, 02 Nov 2012 11:58 pm CET"
at java.text.DateFormat.parse(Unknown Source)
at Main.main(Main.java:10)
Can anyody help me? Because this code doesn't work.
It appears Android's z does not accept time zones in the format XXX (such as "CET"). (Pulling from the SimpleDateFormat documentation.)
Try this instead:
String time = "Fri, 02 Nov 2012 11:58 pm +0100"; // CET = +1hr = +0100
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE, dd MMM yyyy hh:mm aa Z"); // Capital Z
Date date = parseFormat.parse(time);
SimpleDateFormat displayFormat =
new SimpleDateFormat("dd.MM.yyyy, HH:mm");
System.out.println("output is " + displayFormat.format(date));
output is 02.11.2012, 22:58
Note: Also, I think you meant hh instead of HH, since you have PM.
Result is shown here. (This uses Java7's SimpleDateFormat, but Android should support RFC 822 timezones (+0100) as well.)
NB: Also, as it appears Android's z accepts full names ("Pacific Standard Time" is the example they give), you could simply specify "Centural European Time" instead of "CET".
Try out the following code:
SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMMdd");
System.out.println(date_format.format(cal.getTime()));
It will work.. If not print the log cat? What erroe is coming?
First of All I must agree with #Eric answer.
You just need to remove "CET" from your string of date.
Here is sample code. Check it.
String time = "Fri, 02 Nov 2012 11:58 pm CET";
time = time.replaceAll("CET", "").trim();
SimpleDateFormat displayFormat =
new SimpleDateFormat("dd.MM.yyyy, HH:mm");
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm aa");
Date date = null;
try {
date = parseFormat.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output is " + displayFormat.format(date));
Related
Here is my original code-
String dateString = "23 Dec 2015 1:4 PM";
Locale locale = new Locale("en_US");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
Date date = null;
try {
date = formatter.parse(dateString);
} catch (ParseException e) {
LOGGER.error(e);
}
String newDate = df.format(date);
System.out.println("oldDate = " + dateString);
System.out.println("newDate = " + newDate);
and here is my output-
oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 AM
There is AM-PM difference between the oldDate and newDate. Now I changed the DateFormat code to-
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm a", locale);
and I get the expected output, which is-
oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 PM
I'm aware that HH signifies the 24 hour format and hh signifies the 12-hour format.
My question is
If I use HH:mm a instead of hh:mm a, shouldn't this be returning the time in 24-hour format?
(or)
If it defaults to 12-hour format, shouldn't it return respective AM/PM marker depending on the date input provided?
This is just for my understanding.
Updated Answer
Here the problem is with Program flow
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
this simple date formatter is used to format the date string the Date object is created, here is the important part of answer
As you are using HH instead of hh, the SimpleDateFormater considers that provided date string is in 24-Hour Format and simply ignores the AM/PM marker here.
The Date Object from constructed from this SimpleDateFormatter is passed to the
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
That's why it's printing
newDate = 23 Dec 2015 01:04 AM
if you change the line
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
with
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
Everything will go smooth as it should!
Note : when creating a locale you should pass the language code to the Locale() constructor. en-us not en_us.
IMP : Code is tested on Java 8 also. Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Difference between hh:mm and HH:mm:
HH:mm => will look like 00:12, 23:00... this has 24 hour format.
hh:mm => will look like 01:00Am, 02:00Am,...01:00pm this has 12 hour format.
And the a in hh:mm a or in HH:mm a is Am/pm marker for more info go to link
A simple test is the best answer to how the pattern "HH:mm a" is interpreted. First let us investigate the printing mode:
The old format engine SimpleDateFormat:
Calendar cal = new GregorianCalendar(2015, 3, 1, 17, 45);
SimpleDateFormat sf = new SimpleDateFormat("HH:mm a", Locale.US);
System.out.println(sf.format(cal.getTime())); // 17:45 PM
Java-8 (with the new package java.time.format):
LocalTime time = LocalTime.of(17, 59);
DateTimeFormatter tf = DateTimeFormatter.ofPattern("HH:mm a", Locale.US);
System.out.println(tf.format(time)); // 17:59 PM
Here we don't observe any override in both cases. I prefer that approach because using the combination of "HH" and "a" is in my opinion rather an indication for a programming error (the user has obviously not thought enough about the meaning and official description of those pattern symbols).
Now let us investigate the parsing mode (and we will use strict mode to observe what is really going behind the scene):
String dateString = "23 Dec 2015 1:4 PM";
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy H:m a", Locale.US);
df.setLenient(false);
Date date = df.parse(dateString);
// java.text.ParseException: Unparseable date: "23 Dec 2015 1:4 PM"
How is the behaviour in Java-8? It is the same but with a clearer error message:
DateTimeFormatter tf = DateTimeFormatter.ofPattern("H:m a", Locale.US);
tf = tf.withResolverStyle(ResolverStyle.STRICT);
LocalTime.parse("1:4 PM", tf);
// DateTimeException: Cross check failed: AmPmOfDay 0 vs AmPmOfDay 1
This message tells us that the parsed hour (in 24-hour format!) with value "1" indicates AM while the text input contains the other parsed AM/PM-value "PM". This ambivalence cannot be resolved.
Lesson: We have to be careful with lenient parsing where contradictious information can be ignored and lead to false assumptions. The accepted answer of #Arjun is completely wrong.
By the way: Please use Locale.US or new Locale("en", "US") instead of new Locale("en-US") because the language "en-US" does not exist.
Consider the snippet:
String dateStr = "Mon Jan 32 00:00:00 IST 2015"; // 32 Jan 2015
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
gives me the output as
01.02.2015 // Ist February 2015
I wish to prevent this to make the user aware on the UI that is an invalid date?
Any suggestions?
The option setLenient() of your SimpleDateFormat is what you are looking for.
After you set isLenient to false, it will only accept correctly formatted dates anymore, and throw a ParseException in other cases.
String dateStr = "Mon Jan 32 00:00:00 IST 2015"; // 32 Jan 2015
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
try {
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
} catch (ParseException e) {
// Your date is invalid
}
You can use DateFormat.setLenient(boolean) to (from the Javadoc) with strict parsing, inputs must match this object's format.
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
ddMMyyyy.setLenient(false);
Set the date formatter not to be lenient...
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
I am trying to convert the date from May 15, 2009 19:24:11 PM MDT to 20090515192411.
But when I tried the below code, the readformat itself is taking the input as May 16 instead of May 15
Here is my code.
String dateInString = "May 15, 2009 19:24:11 PM MDT";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss a z");
DateFormat writeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = null;
try {
date = readFormat.parse(dateInString);
}
catch(ParseException e) {
e.printStackTrace();
}
System.out.println(date); // Prints May 16, 2009 07:24:11 AM MDT
String formattedDate = "";
if( date != null ) {
formattedDate = writeFormat.format(date);
}
System.out.println(formattedDate); // Prints 20090516072411
Thanks for the help in advance.
String dateInString = "May 15, 2009 19:24:11 PM MDT";
is invalid, time could be either 24 hour format or it could have AM/PM
You need HH instead of hh to read a time in 24-hour format. Java's "lenient dates" are doing you in here - 19:24pm is being parsed as 8 hours after 11:24pm.
This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 9 years ago.
I am facing the problem while converting the date:
Current format is:Thu Sep 05 12:07:46 IST 2013(dow mon dd hh:mm:ss zzz yyyy)
I need to convert in to:09/04/2013 11:38 PM PDT(mm/dd/yyyy hh:mm a zzz)
But i am not able to convert.
Try using SimpleDateFormatter. You have to tell it the input/output format, you can do that based on this description (you can also find a few common examples there).
The code will be something like this:
try {
String input = "Thu Sep 05 12:07:46 IST 2013";
DateFormat formatter = new SimpleDateFormat("I leave this to you :-)))");
System.out.println(formatter.parse(input));
} catch (ParseException e) {
e.printStackTrace();
}
Hope that helps.
You can do this
TimeZone tz = TimeZone.getTimeZone("PST8PDT"); // example
// required format. Remember M is for month, m for miniute
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a zzz");
df.setTimeZone(tz);
String text = df.format(new Date());// current time
System.out.println(text);
Also please check this TimeZones in Java
You try to convert dateformat and timeZone as well, so you need to convert the timezone in your code.
SimpleDateFormat sf = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
isoFormat.setTimeZone(TimeZone.getTimeZone("PDT"));
Date date = isoFormat.parse("mm/dd/yyyy hh:mm a zzz");
this may help you.
try {
DateFormat dffrom = new SimpleDateFormat("E MMM dd hh:mm:ss zzz yyyy");
DateFormat dfto = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a zzz");
Date date = dffrom.parse("Thu Sep 05 12:07:46 IST 2013");
String s = dfto.format(date);
System.out.println(s);
} catch (ParseException e) {
}
OutPut
09/05/2013 00:07:46 AM IST
update
try {
DateFormat dffrom = new SimpleDateFormat("E MMM dd hh:mm:ss zzz yyyy");
DateFormat dfto = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a zzz");
TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
dfto.setTimeZone(zone);
Date date = dffrom.parse("Thu Sep 05 12:07:46 IST 2013");
String s = dfto.format(date);
System.out.println(s);
} catch (ParseException e) {
}
output
09/04/2013 11:37:46 AM PDT
I am trying to convert a String DateTime value which is present in a flat file as a Date object after parsing the flat file in my code.
I have written the code to do that but when I format the date its always giving me a date more than 1 day for the specified value, some times it's adding 5:30.
Below is the code for that:
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy");
Date date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + date);
The output for the above is
---date----Wed Aug 24 08:30:03 IST 2011
Can you please let me know whats the issue here. Is there a problem in the pattern that I am using in the SimplaDateFormat class or is there a problem with the code.
I have been scratching my head on this for a long time now.
Can you please let me know whats the issue here.
Sure. You're effectively calling date.toString(), which doesn't know anything about the SimpleDateFormat which was used to parse the original text value. A Date is just an instant in time. It has no notion of a per-instance format. Additionally, it doesn't know about a time zone. You've given a value in PDT, which was then parsed... and when you print it, it's using the system local time zone (IST). That's what Date.toString always does.
If you want to format a Date in a particular way, using a particular format in a particular time zone, call DateFormat.format.
Your system timezone is different. The output is showing IST - or Indian Standard Time, which is an 12.5h difference from PDT. The code is properly parsing the given date which is PDT (UTC -7) and printing out IST (UTC +5h30).
Java stores Dates as UTC dates. So when you parse the PDT date, Java will convert it to UTC and store it internally as a UTC timestamp. When you print, if you do not specify the timezone, it will default to the system timezone, which in your case would appear to be IST.
To specify an exact timezone, specify it in the SimpleDateFormat:
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy");
f.setTimeZone(TimeZone.getTimeZone("PDT"));
Date date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + f.format(date));
Because you are not formatting a date. Look at the example
public static void main(String[] args){
Locale currentLocale = Locale.US;
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
Date date = null;
Date today;
try {
today = new Date();
String result = f.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("---date----" + f.format(date));
}
will output
Locale: en_US
Result: Tue Sep 25 19:12:38 EEST 2012
---date----Tue Aug 23 20:00:03 PDT 2011
Now, you have a bit modified code
public static void main(String[] args){
Locale currentLocale = Locale.US;
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
DateFormat f2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
Date date = null;
Date today;
try {
today = new Date();
String result = f.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + f.format(date));
System.out.println("---date----" + f2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
which outputs to
Locale: en_US
Result: Tue Sep 25 20:42:10 EEST 2012
---date----Tue Aug 23 20:00:03 PDT 2011
---date----Wed Aug 24 06:00:03 EEST 2011
seems that SimpleDateFormat don't care about timezone even if 'z' pattern is specified. It is setting the timezone when it parses the input. That's how I can describe that a strange behavior. Then use of 'z' pattern seems obsolete and lead to unpredictable results.
so setting the TimeZone will fix the issue
f2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));