Cannot parse date with LocalDateTime - java

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

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();
}

How to convert date from mm/dd/yyyy to mm dd, yyyy

I want to convert date from 07/02/2019 to July 07, 2019. My input value is 07/02/2019 I want to compare with target value July 07, 2019....Please help me on this...
public static void main(String[] args) throws ParseException {
String sDate1="07/01/2019";
java.util.Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(sDate1);
System.out.println(date1);
Output:Mon Jul 01 00:00:00 IST 2019 which is not my expected value
Try this one.
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
SimpleDateFormat output = new SimpleDateFormat("MMMM dd, yyyy");
Date data = sdf.parse("07/02/2019");
String newDate = output.format(data);
System.out.println(newDate);
Here, you use:
java.util.Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(sDate1);
to parse a date that comes in as String.
Then you print that date without any formatting information.
Thus the answer is quite simple: define a pattern for formatting a Date object as string! Same rules, same patterns. Just not parsing, but formatting for printing!
In other words: you already know the concept, you used a formatter to turn a String into a Date. Now simply turn that around, and provide a pattern to a formatter to turn a Date into a string!
Parse your input date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
LocalDate date = LocalDate.parse(sDate, formatter);
Similarly parse your target date
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MMMM dd, uuuu", Locale.ENGLISH);
LocalDate targetDate = LocalDate.parse("July 07, 2019");
Or better yet, define your target date without using a string
LocalDate targetDate = LocalDate.of(2019, Month.JULY, 7);
Compare
if (date.equals(targetDate)) {
System.out.println("Same date");
}
LocalDate also have methods isBefore and isAfter.
This answer is entered from my tablet without trying the code out, so please forgive the typos.

How to convert unix time format to day format month date yeear and time format in java

My time format is coming
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
2108-03-27T17:18:16.985+0530
input Date I have to convert it into other time format
Mar 27,2018 5:18 pm
is expected output can any please suggest me how to convert given time to other time format in java .
SimpleDateFormat sdf = new SimpleDateFormat("MMM d,yyyy h:mm a");
System.out.println(sdf.format(date));
If you have Java 8, use the java.time API:
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendPattern("XX")
.toFormatter();
OffsetDateTime odt = OffsetDateTime.parse("2108-03-27T17:18:16.985+0530", parser);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM dd,yyyy h:mm a", Locale.ENGLISH);
String formattedDate = fmt.format(odt); // Mar 27,2108 5:18 PM
SimpleDateFormat has lots of problems, many of them solved by java.time API, and you should prefer to use those.
For older versions of Java, there's a nice backport, with the same classes and functionality.
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
System.out.println(sdf.format(new Date()));
//Mar 27, 2018 06:28 PM
for more
What are the date formats available in SimpleDateFormat class?
You can convert type any-to-any of date format.
You just need to pass String format to SimpleDateFormate.
Use this method as static and call it from anywhere by passing inputDate
Simplified Date convert method:
public static String getFormattedDate(String inputDate)
{
String outputFormattedDate = "";
try
{
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z");
Date inputFormatDate = inputFormat.parse(inputDate);
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd,yyyy h:mm a");
outputFormattedDate = outputFormat.format(inputFormatDate);
}
catch (Exception ex)
{
outputFormattedDate = inputDate;
ex.printStackTrace();
}
return outputFormattedDate;
}
Hope it will help you.

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

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