Parse date based on locale using simpledateformatter - java

I am getting the date in long format like this :
Wednesday, August 1, 2018
I want this in the below format:
Wed, Aug 01, 2018
I used the below code:
public static String getShortDate(Date date){
SimpleDateFormat format = new SimpleDateFormat("E, MMM dd, yyyy");
return format.format(date);
}
This works fine for en_US. But how to make it work for other locales
For example the long format for German is :
Samstag, 16. Juni 2018
how to get the above short format for it?
The getShortDate method parameter takes Date, but I can change it to String.
If the longer format is : Samstag, 16. Juni 2018
i need it to be : Sa., 16. Jun. 2018
i am using the below code :
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM, yyyy", locale);
return format.format(date);
This is giving me output as: Sa, 16 Jun, 2018
How to get that dot(.) after Sa

To get short date format in different locale code, you could try below code:
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("E, MMM dd, yyyy", new Locale("de", "de"));//for german germany
String date = simpleDateFormat.format(new Date());
Output:
Di, Mär 27, 2018

Related

SimpleDateFormat is not able to parse the date with offset value like - 'GMT-0500'

I am trying to parse this (and many similar) dateString - "Wed Aug 26 2020 11:03:30 GMT-0500"
Looking at the SimpleDateFormat documentation, I was assuming that a pattern like this should work:
String dateFormat = "EEE MMM d yyyy HH:mm:ss z";
However, it doesn't. But the following format is able to parse
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'z";
But when I print the parsed date, I get the time with an hour added and offset reduced by an hour - Wed Aug 26 12:03:30 GMT-04:00 2020
What can I do to prevent this offset change?
Here is the sample code:
String dateStr = "Wed Aug 26 2020 11:03:30 GMT-0500";
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'z";
Date date = new SimpleDateFormat(dateFormat).parse(dateStr);
System.out.println("Original Date String : "+dateStr);
System.out.println("Original Date Object : "+date);
Output:
Original Date String : Wed Aug 26 2020 11:03:30 GMT-0500
Original Date Object : Wed Aug 26 12:03:30 GMT-04:00 2020
Use java.time.OffsetDateTime here because there is no zone in that String, just an offset and the classes you are using are outdated for good reasons... Get rid of java.util.Date and java.text.SimpleDateFormat.
See this example:
public static void main(String[] args) {
// provide the String to be parsed
String dateStr = "Wed Aug 26 2020 11:03:30 GMT-0500";
// provide a matching pattern
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'Z";
// create a formatter with this pattern and a suitable locale for unit names
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat, Locale.ENGLISH);
// parse the String to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dateStr, dtf);
// print the result in the default format
System.out.println("Default/ISO format:\t" + odt);
// and print it in your custom format
System.out.println("Custom format:\t\t" + odt.format(dtf));
}
Output:
Default/ISO format: 2020-08-26T11:03:30-05:00
Custom format: Wed Aug 26 2020 11:03:30 GMT-0500

Difference between hh:mm a and HH:mm a

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.

wrong date in SimpleDateTime parse

This is the string that I have:
Sat, Nov 02, 2013 at 5:10 pm
I'm trying to parse it into a date time using this formatter:
DateFormat formatter = new SimpleDateFormat("EEE, MMM dd, YYYY 'at' K:mm a");
However, this is what it returns when I use it to parse the date string:
Sat Jan 05 17:10:00 CST 2013
I assume I'm getting the formatter wrong, but I can't figure out where.
Capital YYYY is the format for something called the "week year". You want the lowercase yyyy for the actual year.
DateFormat formatter = new SimpleDateFormat("EEE, MMM dd, yyyy 'at' K:mm a");
With this change I output the parsed date and get:
Sat Nov 02 17:10:00 PDT 2013
(I'm in the Pacific time zone.)

Error by converting date: Unparseable date in JAVA

I can't find the problem. I'm trying to convert the date:
"Thu, 10 Jul 2014 13:33:26 +0200"
from string to Date with this code:
String formatType = "EEE, dd MMM yyyy HH:mm:ss Z";
Date startzeit = new SimpleDateFormat(formatType).parse(einsatz.getString("startzeit"));
but I'm getting this exceptoin:
java.text.ParseException: Unparseable date: "Thu, 10 Jul 2014 13:33:26 +0200"
You're creating a SimpleDateFormat without specifying a locale, so it'll use the default locale. By the looks of your variable names, that may not be English - so it'll have a hard time parsing "Thu" and "Jul".
Try:
String formatType = "EEE, dd MMM yyyy HH:mm:ss Z";
Date startzeit = new SimpleDateFormat(formatType, Locale.US)
.parse(einsatz.getString("startzeit");
(That works for me, with your sample value.)

Java new Date with time stamp in date format

I have used the following
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss zzz");
Date date = new Date();
String formattedDate= df.format(date);
Date dateWithTime = df.parse(formattedDate);
i got the formatted date as string when i conver this into date i got error like
java.text.ParseException: Unparseable date: "Tue Feb 26 11:45:43 IST 2013"
How would convert to date or how i format a current date and get as date?
I think your code wouldn't throw ParseException. But it sure would definitely yield wrong output. your format should be:
"dd-MM-yyyy hh:mm:ss zzz"
Note that
MM---> Months
mm---> Minutes
Test with your code with out correcting the format:
Sat Jan 26 06:24:07 GMT 2013
Test with your code with correcting the format:
Tue Feb 26 06:20:51 GMT 2013
The date format should be as follows as shown in the exception. Change it to -
EEE MMM d hh:mm:ss z yyyy
The correct simpledateformat will be
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Please refer the link for proper date formatting and parsing
SimpleDateFormat

Categories

Resources