Parse a string to Date without locale - java

I need to parse a String to Date in Java. The problematic scenario is when the full date pattern is used and it depends on a specific locale (that I don't know previously)
For example, using pattern "EEEE dd MMMM yyyy" two possible inputs are:
English = "Friday 10 November 2014"
Spanish = "Viernes 10 Noviembre 2014"
Is it possible to convert the above inputs to a Date object without to know the source locale?
Thanks.

I try the MadProgrammer solution and it works:
String dateInString = "Friday 10 November 2014";
//String dateInString = "Viernes 10 Noviembre 2014";
Locale localeList[] = DateFormat.getAvailableLocales();
Date date = null;
for (Locale l : localeList) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("EEEE dd MMMM yyyy", l);
date = formatter.parse(dateInString);
System.out.println("Trying with locale: " + l.toString());
break;
} catch (ParseException e) {
}
}
Thanks

Related

How can i get simple yyyy-MM-dd out of this date?

I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
} catch (ParseException e) {
e.printStackTrace();
}
For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?
Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
// get / provide the String to be parsed
String expDate = "31.12.2032";
// provide a pattern that parses such a date
String pattern = "dd.MM.uuuu";
// create a DateTimeFormatter with this pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
// parse the String with the DateTimeFormatter
LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
// print the default format of a LocalDate
System.out.println(expLocalDate);
// print the LocalDate using the pattern created for parsing
System.out.println(expLocalDate.format(dtf));
// create a totally different DateTimeFormatter inline and format the date differently
System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
Locale.ENGLISH)));
}
The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032
Try this way
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
format1.format(date);
expDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Parsing string to date with timezone in national format

I try to parse string (russian locale) "01 августа 2014, пятница. 20:00 МСК" to java.util.Date. I try this code:
String dateString = "01 августа 2014, пятница. 20:00 МСК"
Locale rusLocale = new Locale.Builder().setLanguage("ru").setScript("Cyrl").build();
String pattern = "dd MMMM yyyy, EEEE. HH:mm z"
Date date = SimpleDateFormat(pattern, rusLocale).parse(dateString)
With month and weekday this code work fine, but when I try to parse string with timezone name МСК I get java.text.ParseException: Unparseable date. When I change MCK to MSK "01 августа 2014, пятница. 20:00 MSK" code also work fine. So we can parse strings month and weekday, but can't do it with timezone or "MCK" is just not valid?
Try this code. I think it is something relevant with your code.
String dateString = "17 октябрь 2014, пятница. 20:00";
Locale rusLocale = new Locale.Builder().setLanguage("ru").setScript("Cyrl").build();
String pattern = "dd MMMM yyyy, EEEE. HH:mm";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, rusLocale);
dateFormat.setTimeZone(TimeZone.getTimeZone("МСК"));
Date date = dateFormat.parse(dateString);
} catch (ParseException e) {
...

Trouble parsing Java Date Object?

I am receiving a Java Date formatted like so: "Sun Sep 14 02:00:00 PDT 2014" into a yyyy-MM-dd format but I can't seem to parse it. What I tried is the following:
String time = "Sun Sep 14 02:00:00 PDT 2014";
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date contractEffectiveDateFormat = f.parse(time);
System.out.println("Date: " + contractEffectiveDateFormat);
However, I get an error saying that this date is unparsable. I'm not sure how to go about parsing this date because if I try to parse the date using the following:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
which is how to actually parse the date correctly into a Date object,
the string would turn into a Date object, but I can't seem to do anything with it from there. I want to turn it in so that it looks like 2014-09-14. Any ideas on how to do so? Thanks!
Use two DateFormat(s) one for input and for output,
String time = "Sun Sep 14 02:00:00 PDT 2014";
DateFormat out = new SimpleDateFormat("yyyy-MM-dd");
DateFormat in = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
try {
Date effectiveDate = in.parse(time);
System.out.println("Date: " + out.format(effectiveDate));
} catch (ParseException e) {
e.printStackTrace();
}
Output is the requested
Date: 2014-09-14
Your incoming string is this String time = "Sun Sep 14 02:00:00 PDT 2014";
which means the SimpleDateFormat pattern should match the incoming String pattern so you need to use SimpleDateFormat like this
DateFormat inFormat=new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy",Locale.ENGLISH);
Then when you called parse() on inFormat it will give you Date Object which doesnot have particular format associated with it. So in order to format the Date again you need to create SimpleDateFormat object specifying the format you want which is this
DateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Ultimately bind all together
One more thing always specify the Locale
String time = "Sun Sep 14 02:00:00 PDT 2014";
DateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
// good practice to specify the locale
DateFormat inFormat=new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy",Locale.ENGLISH);
try {
Date parsedDate = inFormat.parse(time);
System.out.println("Required Formatted Date: " + outFormat.format(effectiveDate));
} catch (ParseException e) {
e.printStackTrace();
}
Simply add another SimpleDateFormat that'll allow you to present the Date object the way you want:
public static void main(String[] args) throws ParseException {
String time = "Sun Sep 14 02:00:00 PDT 2014";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
Date contractEffectiveDateFormat = df.parse(time);
System.out.println("Date: " + contractEffectiveDateFormat);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(f.format(contractEffectiveDateFormat)); // prints 2014-09-14
}

Java. Cant parse date using DateFormat

I have a date string:
Thu Feb 20 08:00:00 EET 1992
And using this code to format it:
String datePatternFrom = "EEE MMM dd HH:mm:ss ZZZ yyyy";
String datePatternTo = "MMM dd, yyyy";
String prettyDate = "";
try {
DateFormat fromFormatter = new SimpleDateFormat(datePatternFrom);
Date date = (Date)fromFormatter.parse(userBirthday.toString());
DateFormat toFormatter = new SimpleDateFormat(datePatternTo);
prettyDate = toFormatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
Why I'am getting the exception?
java.text.ParseException: Unparseable date: "Thu Feb 20 08:00:00 EET 1992" (at offset 0)
The problem is with the weekday and month and your locale.
Thu is English, so you have to tell the parser that it should use English weekdays:
DateFormat fromFormatter = new SimpleDateFormat(datePatternFrom, Locale.US);
This will work for your pattern.
If you do not specify a locale, the default will be used, which is not always an English one. ;-)
It could be your locale. Try making a SDF with datePatternFrom, give it a date to format and print that somewhere. See what pops up.
Probably your userBirthday object was not created as a java.util.Date object. Can you try a System.out.println(userBirthday.getClass().getName());?

struck in parsing custom data format in java

I am trying to parse the date in a particular custom format.
WEDNESDAY 25th JAN 2012 - 12:44:07 PM
like this..
I created a SimpleDateFormat for this..
SimpleDateFormat sdf = new SimpleDateFormat("EEEE DD MMM YYYY - HH:MM:SS aa" );
the problem is the literal for the days. it is coming like 25th, 23rd, 02nd.I am getting exception for this thing...
help how to overcome this problem.
You can remove the literal for the day using a regex like this.
String dateString = "WEDNESDAY 25th JAN 2012 - 12:44:07 PM";
SimpleDateFormat format = new SimpleDateFormat("EEEEEEE dd MMM yyyy - HH:mm:ss aa", new Locale("EN"));
dateString = dateString.replaceAll("(.*[0-9]{1,2})(st|nd|rd|th)(.*)", "$1$3");
Date parsedDate = format.parse(dateString);
System.out.println(parsedDate);
(Ignore the Locale, i'm from somewhere else :) )
You could split the date string you're trying to parse into parts and remove the offending two letters in the following way:
String text = "WEDNESDAY 21st JAN 2012 - 12:44:07 PM";
String[] parts = text.split(" ", 3); // we only need 3 parts. No need splitting more
parts[1] = parts[1].substring(0, 2);
String parseableText = String.format("%s %s %s", parts[0], parts[1], parts[2]);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMM yyyy - hh:mm:ss aa" );
try {
java.util.Date dt = sdf.parse(parseableText);
} catch (ParseException e) {
e.printStackTrace();
}
Your parse string had some errors in it as well. Case is important for the date and time ptterns. See the SimpleDateFormat javadoc for a reference.
You are going to have to manually do it somehow.
e.g. A method as follows:
public static String makeItParseable(String dateStr) {
if(dateStr.contains("st ")) {
return dateStr.replace("st ", " ");
} else if(dateStr.contains("nd ")) {
return dateStr.replace("nd ", " ");
} else if(dateStr.contains("rd ")) {
return dateStr.replace("rd ", " ");
} else {
return dateStr.replace("th ", " ");
}
}
And use it make the input string parseable:
String dateStr = "WEDNESDAY 1st JAN 2012 - 12:44:07 PM";
dateStr = makeItParseable(dateStr);
DateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy - hh:mm:ss a");
Date date = dateFormat.parse(dateStr);
Add ".th" to the format string, following what people stated in this thread
How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)

Categories