Can't get LocalDate to Parse correctly - java

String date = "08/02/2022 Tuesday";
DateTimeFormatter LONG_DATE_FORMAT_ddMMyyyyEEEE = ofPattern("dd/MM/yyyy EEEE");
LocalDate.parse(date, LONG_DATE_FORMAT_ddMMyyyyEEEE);
I'm getting a DateTimeParseException with the following message: Text 08/02/2022 Tuesday' could not be parsed at index 11.
I suppose this is an issue with the EEEE side of my format, but I can't seem to understand what should replace it.
This is java 1.8.0_311

We need DateTimeFormatter class to format date string properly. We also need to convert the string date to LocalDate object and back to string again to display. The DateTimeParseException class handles any undesired outcomes.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class Main {
public static void main(String[] args) {
try{
String date = "08-02-2022 Tuesday";
DateTimeFormatter pattern =
DateTimeFormatter.ofPattern("dd-MM-yyyy eeee");
// parsing string date to LocalDate obj
// The part you were missing
LocalDate formattedDate = LocalDate.parse(date, pattern);
// Again converting to string
System.out.println(formattedDate.format(pattern));
}
// handling exception for unparseble dates
catch(DateTimeParseException x){
System.out.println("The given date cannot be parsed");
}
}
}

LocalDate contains of a day, month, and year (Variation between +999999999-12-31 and -999999999-12-31)
Things like time and other values are rejected by the parsing. If you would like the day of the week, you can use a function like:
// Parses the date
LocalDate dt = LocalDate.parse("2018-11-27");
// Prints the day
System.out.println(dt.getDayOfWeek());

This works for me:
String date = "08/02/2022 Tuesday";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy EEEE");
LocalDate time = LocalDate.parse(date, formatter);
System.out.println(time.format(formatter));

Related

How to convert date and time object 12 hours format?

I get date and time from client in the controller, here the signature of the function:
public ResponseEntity<Meeting> create(#RequestParam(name = "start") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start)
if I print the start variable it shows date and time in 24-hour format:
2020-12-10T16:52:42.014982500
But I want the value of the LocalDateTime variable will be in 12 hours format, so I tried to change DateTimeFromat in the function's signature
public ResponseEntity<Meeting> create(#RequestParam(name = "start") #DateTimeFormat(DateTimeFormatter.ofPattern("dd/MM/yyyy hh.mm aa")) LocalDateTime start).3
But on this row:
DateTimeFormatter.ofPattern("dd/MM/yyyy hh.mm aa")
I get error:
Attribute value must be constant
My question is what params #DateTimeFormat have to get so it can convert date and time from client to 12 hours format?
A date-time object does not store the formatting information. A LocalDateTime is supposed to store just the date and time components (i.e. year, month, day of the month, hour, minute, second and the fraction of second). When you print an object of LocalDateTime, you get what its toString function returns. If you need the value in a different format, you need to get a formatted string out of this object but in no case, you will be able to store the format into the instance of LocalDateTime.
Given below is a simple demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String strDateTime = "2020-12-10T16:52:42.014982500";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu hh.mm a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDateTime);
System.out.println(ldt);// Prints the value of ldt#toString
// Get a formatted string
String formatted = ldt.format(dtf);
System.out.println(formatted);
}
}
Output:
2020-12-10T16:52:42.014982500
10/12/2020 04.52 PM
Update
From your comment on the other answer (which has been deleted now), I learnt that your date-time string is 2020-12-08T21:34:18.119+00:00 which has a zone offset information (+00:00) and therefore, the most appropriate type would be OffsetDateTime.
Change the annotation as
public ResponseEntity<Meeting> create(#RequestParam(name = "start") #DateTimeFormat(pattern = DateTimeFormatter.ISO_ZONED_DATE_TIME) OffsetDateTime start)
or
public ResponseEntity<Meeting> create(#RequestParam(name = "start") #DateTimeFormat(iso = ISO.DATE_TIME) OffsetDateTime start)
Check the Spring documentation page to learn more about the second option.
A quick demo:
import java.time.OffsetDateTime;
class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2020-12-08T21:34:18.119+00:00");
System.out.println(odt);
}
}
Output:
2020-12-08T21:34:18.119Z

2020-04-03 20:17:46 to "yyyy-MM-dd'T'HH:mm:ss" format

Is there any way in java(java.util.* or Joda api ) to convert "2020-04-03 20:17:46" to "yyyy-MM-dd'T'HH:mm:ss"
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.parse("2020-04-03 20:17:46")
its giving java.text.parseException always
Just for the case you are using Java 8 or above, make use of java.time.
See this simple example:
public static void main(String[] args) {
// example datetime
String datetime = "2020-04-03 20:17:46";
// create a formatter that parses datetimes of this pattern
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// then parse the datetime with that formatter
LocalDateTime ldt = LocalDateTime.parse(datetime, parserDtf);
// in order to output the parsed datetime, use the default formatter (implicitly)
System.out.println(ldt);
// or format it in a totally different way
System.out.println(ldt.format(
DateTimeFormatter.ofPattern("EEE, dd. 'of' MMM 'at' hh-mm-ss a",
Locale.ENGLISH)
)
);
}
This outputs
2020-04-03T20:17:46
Fri, 03. of Apr at 08-17-46 PM
Please note that this doesn't consider any time zone or offset, it just represents a date and time consisting of the passed or parsed years, months, days, hours, minutes and seconds, nothing else.
Do not use Date/Time API from java.util.* as most of them are now outdated. Use java.time API instead.
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) throws IOException {
String strDatetime = "2020-04-03 20:17:46";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDate = LocalDateTime.parse(strDatetime, formatter);
System.out.println(parsedDate);
}
}
Output:
2020-04-03T20:17:46
Learn more about DateTimeFormatter at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Could this help you? http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
First you need to parse the String with the old format, you will get a Date object. Then Create a new SimpleDateFormat with your new format, then you can format the Date object.
String dateString = "2020-04-03 20:17:46";
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
String formattedDate = output.format(date);
It do not work that way directly but if you still want to do it then, here is the process.
Create an object of SimpleDateFormat with pattern "yyyy-MM-dd HH:mm:ss")
use this to parse the string. Ultimately you are going to get date in both cases. Is there any specific reason for using T in pattern for dates which do not contain them?
Use LocalDateTime.
Timestamp timestamp = Timestamp.parse("2020-04-03 20:17:46");
LocalDateTime localDateTime = timestamp.toLocalDateTime();
System.out.println(localDateTime); // 2020-04-03T20:17:46

Error converting date with two digits for the Year field

// input format: dd/MM/yy
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("12/1/20"))); // 0020-11-01
I am using the above code but it is giving me year as '0020' instead of '2020'.
Use java.time for this:
public static void main(String[] args) {
String dateString = "12/1/20";
LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/M/yy"));
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output is
2020-01-12
Pay attention to the amount of M in the patterns, you cannot parse a String that contains a single digit for a month using a double M here.
Most Java devs would be tempted to answer SimpleDateFormat but it's not thread safe.
So I recommend you use Java 8 DateFormat.
Assuming your current Date is a String:
DateFormat dateFormat = new DateFormat("yyyy-MM-dd") ;
String dateString ="20/4/20";
LocalDate date = LocalDate.parse(dateString, dateFormat);
If you are using less than Java 8 use joda time for the same classes.
Once you have converted it as a date object use required format and use LocalDate.
format(date, new DateFormat("yyyy-MM-dd")) ;

How to convert String e.g. "01/01/2019" to date in Java 8 [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 4 years ago.
I'm trying to use Java 8's DateTimeFormatter to turn strings such as "17/01/2019" into dates of exactly the same format.
I'm currently using:
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH);
LocalDateTime dExpCompletionDate = LocalDateTime.parse(sExpCompletionDate, format);
LocalDateTime dExpCommencementDate = LocalDateTime.parse(sExpCommencementDate, format);
and getting the error:
java.time.format.DateTimeParseException: Text '' could not be parsed at index 0
Which would suggest there's something wrong with my format.
Currently, I've tried using the default format as well as using LocalDate instead of LocalDateTime
You're trying to obtain LocalDateTime instead of LocalDate:
LocalDateTime dExpCompletionDate = LocalDateTime.parse(sExpCompletionDate, format);
Here is a small example with LocalDate:
public static void main(String[] args) {
String sExpCompletionDate = "17/01/2019";
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH);
LocalDate dExpCompletionDate = LocalDate.parse(sExpCompletionDate, format);
// Converts LocalDate into LocalDateTime
LocalDateTime dExpCompletionDate2 = LocalDate.parse(sExpCompletionDate, format).atStartOfDay();
System.out.println(dExpCompletionDate);
System.out.println(dExpCompletionDate2);
}
Output:
2019-01-17
2019-01-17T00:00
Here is an example with LocalDateTime:
public static void main(String[] args) {
String sExpCompletionDate = "17/01/2019 14:22:11";
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
LocalDateTime dExpCompletionDate = LocalDateTime.parse(sExpCompletionDate, format);
System.out.println(dExpCompletionDate);
}
Output:
2019-01-17T14:22:11
Because "dd/MM/yyyy" is date pattern, you can't parse to DateTime with it. What you can do is, parse to Date and then get StartOfDay as DateTime
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDateTime dExpCompletionDate = LocalDate.parse("01/01/2019", format).atStartOfDay();
Use SimpleDateFormat. Here is a working example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample1 {
public static void main(String[] args)throws Exception {
String sDate1="31/12/1998";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
System.out.println("Date is : "+date1);
}
}
For a more comprehensive answer, refer to reply by BalusC.

String to joda LocalDate in format of "dd-MMM-yy"

I am using JAXB and joda time 2.2. to backup the data from Mysql to XML and restore it back. in my Table I have a Date attribute in format of "16-Mar-05". I successfully store this in XML. but when I want to read it from XML and put it back in Mysql table, I cant get the right format.
this is my XMLAdapter class, here in unmarshal method the input String is "16-Mar-05", but I cant get the localDate variable in the format of "16-Mar-05", although I am setting pattern to "dd-MMM-yy". I posted all the options I tried, how can I get my localDate in "dd-MMM-yy" like 16-Mar-05format?
Thanks!!
public class DateAdapter extends XmlAdapter<String, LocalDate> {
// the desired format
private String pattern = "dd-MMM-yy";
#Override
public String marshal(LocalDate date) throws Exception {
//return new SimpleDateFormat(pattern).format(date);
return date.toString("dd-MMM-yy");
}
#Override
public LocalDate unmarshal(String date) throws Exception {
if (date == null) {
return null;
} else {
//first way
final DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
final LocalDate localDate2 = dtf.parseLocalDate(date);
//second way
LocalDate localDate3 = LocalDate.parse(date,DateTimeFormat.forPattern("dd-MMM-yy"));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
return localDate4;
}
}
So I took your code and ran it and it works fine for me...
The problem, I think, you're having is that you're expecting a LocalDate object to maintain the format that you original parsed the object with, this is not how LocalDate works.
LocalDate is a representation of date or period in time, it is not a format.
LocalDate has a toString method which can be used to dump the value of the object, it, this is a internal format used by the object to provide a human readable representation.
To format the date, you need to use some kind of formater, that will take the pattern you want and a date value and return a String
For example, the following code...
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String date = "16-Mar-05";
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
LocalDate localDate2 = dtf.parseLocalDate(date);
System.out.println(localDate2 + "/" + dtf.print(localDate2));
//second way
LocalDate localDate3 = LocalDate.parse(date, DateTimeFormat.forPattern("dd-MMM-yy"));
System.out.println(localDate3 + "/" + dtf.print(localDate3));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
System.out.println(localDate4 + "/" + FORMATTER.print(localDate4));
Produced...
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
Before you get upset about this, this is how Java Date works as well.

Categories