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.
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 have a string of day, date and time that is String myDateString = "Fri, 07 Jun 2013 09:30:00";.For date January 2, 2010 we use new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(mystring);. What can I use instead of MMMM d, yyyy in my situation
Now How can I extract day, year, month, day of the month, hours, minutes and seconds from the string in the following pattern.
day: Fri,
Year: 2013,
Month: Jun,
day of the Month: 07,
Hour: 09,
Minutes: 30 and
Seconds: 00,
Please help me in this respect I would be very thankful to you for this act of kindness. Thanks in advance.
Reference these formats Java Date Format Docs:
try this code:
Date tempDate = new SimpleDateFormat("E, dd MM yyyy HH:mm:ss").parse("Fri, 09 12 2013 09:30:00");
System.out.println("Current Date " +tempDate);
Use a SimpleDateFormat object to extract the date and put it into a util.Date object. From there extract the individual attributes you need.
try this:
String myDateString = "Fri, 07 Jun 2013 09:30:00";
Date myDate = null;
// attempting to parse the String with a known format
try {
myDate =
new SimpleDateFormat("E, dd MMM yy HH:mm:ss", Locale.ENGLISH)
.parse(myDateString);
}
// something went wrong...
catch (Throwable t) {
// just for debug
t.printStackTrace();
}
finally {
if (myDate != null) {
// just for checking...
System.out.println(myDate);
// TODO manipulate with calendar
}
}
This will work if you are certain that the format you receive will always be consistent.
You can then split your date into different values by initializing a Calendar object, then retrieving its various fields.
For instance:
// once you're sure the date has been parsed
Calendar calendar = Calendar.getInstance(myTimeZone, myLocale);
calendar.setTime(myDate);
// prints the year only
System.out.println(calendar.get(Calendar.YEAR));
You can use SimpleDateFormat from standard library. Something like following:
new SimpleDateFormat("E, dd MM yyyy HH:mm:ss").parse(myDateString);
The easiest solution is to split the string
String[] parts = "Fri, 07 Jun 2013 09:30:00".split("[ :,]+");
this will produce an array
[Fri, 07, Jun, 2013, 09, 30, 00]
then use its elements
String dayOfWeek = parts[0];
...
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));
I have given text field expression new.java.util.Date() and pattern MMMMM dd, yyyy as the mentioned format.
The date must display like: jan 13, 2012 but it's displaying in some other format: Fri Jan 13 08:30:12 IST 2012.
So how to print the date in the mentioned format. And one thing in preview the date displays correctly as mentioned but inside my application it displays Fri Jan 13 08:30:12 IST 2012 format. Is there any way to make it to work properly?
new SimpleDateFormat("MMM dd, yyyy ").format(new Date())
Put the above line in text field so you will get your Date format
Use this below method..hope it will help to you
public static String getDateTimeForUgcServer(String date)
{
SimpleDateFormat intputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = new Date();
try
{
dt = intputFormat.parse(date);
}
catch (ParseException e)
{
e.printStackTrace();
}
SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String str = outputFormat.format(dt);
return str;
}