struck in parsing custom data format in java - 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)

Related

Cannot parse date with LocalDateTime

I'm trying to parse a date string using Java8 LocalDateTime without any success.
The exception is: DateTimeParseException: Text '28-APR-2015 01:25:00 PM' could not be parsed at index 3
The string to parse is: 28-APR-2015 01:25:00 PM and the pattern I'm currently using is dd-LLL-yyyy hh:mm:ss a
Where am I wrong?
Thank you
Adding example code:
String text = "28-APR-2015 01:25:00 PM";
DateTimeFormatter fromatter = DateTimeFormatter.ofPattern("dd-LLL-yyyy hh:mm:ss a");
try {
String out = LocalDateTime.parse(text, formatter)
System.out.println(out);
} catch (DateTimeParseException e) {
e.printStackTrace();
}
Solved using the response from #Florin using:
DateTimeFormatter tertiaryFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient().appendPattern("dd-LLL-yyyy hh:mm:ss a").toFormatter();
MMM in English will be Apr
LLL in English will be 4
Please run this snippet - it will explain you a lot:
asList("MMM", "LLL").forEach(ptrn
-> System.out.println(ptrn + ": " + ofPattern(ptrn, Locale.ENGLISH).format(Month.APRIL))
);
Locale.setDefault(Locale.ENGLISH);
String textM = "28-Apr-2015 01:25:00 PM";
DateTimeFormatter formatterM = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a");
System.out.println(LocalDateTime.parse(textM, formatterM));
String textL = "28-4-2015 01:25:00 PM";
DateTimeFormatter formatterL = DateTimeFormatter.ofPattern("dd-LLL-yyyy hh:mm:ss a");
System.out.println(LocalDateTime.parse(textL, formatterL));
If you need to use APR then you need to build your own DateTimeFormatter using DateTimeFormatterBuilder and set parseCaseInsensitive option.
The problem is because of your time pattern issue. you need make sure your time format could matching with the pattern.
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Parse String Date time in java

I have a date time (which is a string) in the following format: 2/19/2015 5:25:35 p.m, and I wanted to turn it in the following Date Format: Thu Feb 19 5:25:35 p.m. CET 2015 I tried the following code:
String sDatePrecedenteExecution = "19/02/2015 17:30:29";
SimpleDateFormat format = new SimpleDateFormat ("ddd d mmm yyyy HH: mm: ss");
Date date = format.parse (sDatePrecedenteExecution)
but I got the following error:
java.text.ParseException: unparseable Date: "2/19/2015 5:30:29 p.m."
Has java.text.DateFormat.parse (DateFormat.java:337)
You are currently using the "output" format to read your incoming date string (2/19/2015 5:25:35 p.m), which is why you see the error.
You need to specify a second format for parsing your incoming date string, and use that format to parse instead. It should look like this:
SimpleDateFormat inFormat = new SimpleDateFormat ("dd/MM/yyyy HH:mm:ss")
Date date = inFormat.parse(sDatePrecedenteExecution)
Note that you also have a bug in your output format - m means minutes, and you want MMM, which is months. Have a look at the docs.
Your SimpleDateFormat doesn't match the format which you are entering. They should reflect the same.
Try this code
String parseDate = ""19/02/2015 17:30:29";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date parsedDate = dateFormat.parse(parseDate);
You need to change your code something like...
String sDatePrecedenteExecution = "19/02/2015 17:30:29";
SimpleDateFormat format = new SimpleDateFormat ("dd/mm/yyyy HH:mm:ss");
try {
Date date = format.parse (sDatePrecedenteExecution);
System.out.println(date);
format = new SimpleDateFormat ("ddd d mmm yyyy HH: mm: ss");
String str = format.format(date);
System.out.println(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this pattern:
SimpleDateFormat format = new SimpleDateFormat ("dd mm yyyy HH:mm:ss");
You went wrong when you made: "ddd d mmm yyyy HH: mm: ss"
Use this pattern "dd/M/yyyy HH:mm:ss" instead & read the documentation
SimpleDateFormat format = new SimpleDateFormat ("dd/M/yyyy HH:mm:ss");
String sDatePrecedenteExecution = "19/02/2015 17:30:29";
try{date =format.parse (sDatePrecedenteExecution);
}catch(Exception ex){//deal with it here}
System.out.println(date.toString()); //Thu Feb 19 17:30:29 UTC 2015

issue in display Date in different format with one string value android

Hello friends i have one string value for date like "2015-02-04" and below is my code
Date todaysDate = new java.util.Date("2015-02-07");
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat df3 = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat df4 = new SimpleDateFormat("MM dd, yyyy");
SimpleDateFormat df5 = new SimpleDateFormat("E, MMM dd yyyy");
SimpleDateFormat df6 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");
try
{
//format() method Formats a Date into a date/time string.
String testDateString = df.format(todaysDate);
System.out.println("String in dd/MM/yyyy format is: " + testDateString);
String str2 = df2.format(todaysDate);
System.out.println("String in dd-MM-yyyy HH:mm:ss format is: " + str2);
String str3 = df3.format(todaysDate);
System.out.println("String in dd-MMM-yyyy format is: " + str3);
String str4 = df4.format(todaysDate);
System.out.println("String in MM dd, yyyy format is: " + str4);
String str5 = df5.format(todaysDate);
System.out.println("String in E, MMM dd yyyy format is: " + str5);
String str6 = df6.format(todaysDate);
System.out.println("String in E, E, MMM dd yyyy HH:mm:ss format is: " + str6);
}
catch (Exception ex ){
System.out.println(ex);
}
my when i run above code i gives me error like
02-05 16:34:28.288: E/AndroidRuntime(27931): Caused by: java.lang.IllegalArgumentException
02-05 16:34:28.288: E/AndroidRuntime(27931): at java.util.Date.parse(Date.java:437)
02-05 16:34:28.288: E/AndroidRuntime(27931): at java.util.Date.<init>(Date.java:149)
02-05 16:34:28.288: E/AndroidRuntime(27931): at com.example.paginationdemo.Demp.onCreate(Demp.java:33)
at line Date todaysDate = new java.util.Date("2015-02-07");
any idea how can i solve it?
Simple: don't use the deprecated new Date(String) constructor. Instead, create a SimpleDateFormat with the right format, and use the parse method.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
Date date = format.parse("2015-02-07");
Always look at compiler warnings such as when you're using deprecated members. They're usually deprecated for a reason!

Parse a string to Date without locale

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

date format in java

My requirement is to get the date in format MM/dd/yy. But I am currently getting the date value as "Sun Dec 31 00:00:00 IST 2006". I tried a sample code for the conversion as follows.
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Please help me to convert the given date into MM/dd/yy
You need to use SDF (SimpleDateFormat) to process the output too.
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(format.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Change your code to:
String pattern = ;
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM/dd/yy");
try {
Date date = inputFormat.parse("12/31/2006");
System.out.println(outputFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
The reason of your output is because you're outputting the date object through System.out.println(date); which is effectively, translated to System.out.println(date.toString());
The toString() method of Date outputs date in the format of:
EEE MMM dd HH:mm:ss zzz yyyy
Here's the code for Date.toString()
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
Your code is correct though. Use SimpleDateFormat to display the date like so:
System.out.println(format.format(date));
You're using the SimpleDateFormat to parse a string, and that's working fine - but then you're using Date's toString method (implicitly) when formatting the date. That will use a default format which is completely independent of the format which was originally used to parse the value.
A Date object knows nothing about how you want to format it. That's what you should be using SimpleDateFormat for.
You can use SimpleDateFormat to format it again:
System.out.println(format.format(date));
... but a better approach would be to switch to Joda Time and use its DateTimeFormatter class, which is thread-safe and immutable, unlike SimpleDateFormat... the rest of its API is better, too.

Categories