Unable to Convert String to localDate with custom pattern [duplicate] - java

This question already has answers here:
How to format LocalDate object to MM/dd/yyyy and have format persist
(4 answers)
Closed 2 years ago.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import java.text.*;
public class ConvertStringToDate {
public static void main(String[] args)throws Exception {
String date = "2020-06-14";
DateTimeFormatter Stringformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, Stringformatter);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String formattedDate = localDate.format(formatter); // output here is as expected 14.06.2020
// facing issues when converting back to localDate with defined pattern,
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter); // expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
// System.out.println(parsedDate);
// System.out.println(parsedDate.getClass().getName());
}
}
Apologizes for my explanation early days with java. Basically i am trying to convert input string "2020-06-14" into a localDate with a custom pattern "dd.MM.yyyy" in the end trying to have a date object not a String. Is there an other way to achieve it.

A date has no format. Therefore when you write
//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
your expectation is simply wrong. The date is parsed according to the formatter but how the date represents the parsed values and how it chooses to display them afterwards no longer has any connection to the formatter.
The only way to get your format back is to write parsedDate.format(formatter) once again and you are back where you started, which is what formattedDate was already.

Related

Can't get LocalDate to Parse correctly

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

How to parse a Date with TimeZone with and without colon [duplicate]

This question already has answers here:
DateTimeFormatter Accepting Multiple Dates and Converting to One (java.time library)
(4 answers)
How to parse dates in multiple formats using SimpleDateFormat
(13 answers)
Generic support for ISO 8601 format in Java 6
(2 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
The below code for date parse works fine for the date "2015-03-25T09:24:10.000+0530" :-
String time = "2015-03-25T09:24:10.000+0530";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
LocalDateTime localDateTime = LocalDateTime.parse(time, timeFormatter);
System.out.println("localDateTime:"+localDateTime);
Also, the below code works fine for the date "2015-03-25T09:24:10.000+05:30"
String time = "2015-03-25T09:24:10.000+05:30";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
LocalDateTime localDateTime = LocalDateTime.parse(time, timeFormatter);
System.out.println("localDateTime:"+localDateTime);
But Im trying to find a pattern which match either "2015-03-25T09:24:10.000+0530" or "2015-03-25T09:24:10.000+05:30". Is that possible without doing stuff like checking whether the input date has colon or not?
I felt adding 'X' towards ending of datePattern would help according to the doc but it didnt. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Any suggestions?
Keep the optional patterns inside the square bracket.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS[XXX][X]", Locale.ENGLISH);
Stream.of(
"2015-03-25T09:24:10.000+0530",
"2015-03-25T09:24:10.000+05:30"
).forEach(s -> System.out.println(OffsetDateTime.parse(s, dtf)));
}
}
Output:
2015-03-25T09:24:10+05:30
2015-03-25T09:24:10+05:30
Learn more about the modern date-time API from Trail: Date Time.
Interesting question. You can use parseBest.
String[] test = {"2015-03-25T09:24:10.000+0530" , "2015-03-25T09:24:10.000+05:30" };
for (String s : test) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS[Z][XXX]");
TemporalAccessor result = formatter.parseBest(s, ZonedDateTime::from, ZonedDateTime::from);
System.out.println(result);
}
This outputs
2015-03-25T09:24:10+05:30
2015-03-25T09:24:10+05:30

How can I convert a String formatted in this way into a Date using Java? [duplicate]

This question already has answers here:
Parse CIM_DateTime with milliseconds to Java Date
(2 answers)
Closed 2 years ago.
Into a Java application I have this String representing a timestamp containing values like this: 2009-10-17 05:45:14.000
As you can see the string represents the year, the month, the day, the hour, the minute, the second and the millisencond.
I have to convert a String like this into a Date object (if possible bringing also the millisecond information, is it possible?)
How can I correctly implement it?
You can use SimpleDateFormat to parse a given string date according to a given pattern, it also supports milliseconds, like this:
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date=format.parse("2009-10-17 05:45:14.050");
Since Java 8, you should use the classes in the date-time API
Class LocalDateTime stores a date and a time up to nanosecond precision.
Here is a snippet showing how to parse a string into an instance of LocalDateTime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateTime {
public static void main(String[] args) {
String str = "2009-10-17 05:45:14.000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(str, formatter);
}
}

How to convert String to Date with a specific format in java [duplicate]

This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Convert String date into java.util.Date in the dd/MM/yyyy format [duplicate]
(1 answer)
return date type with format in java [duplicate]
(1 answer)
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 3 years ago.
I have a requirement to convert String to Date (in dd-MM-yyyy format). But dateformat.parse gives the format with seconds. I need to convert the String date to Date in the same format as mentioned above.
The class Date will always contain both date a nd time information, since it represents an instant in time.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}
As you can see, hours, minutes, seconds and millis get all set to 0.
If you later want to output the date in string format, you need to use the DateFormat#format(Date) method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}
If you'd rather store only date information, you could use the java.time package and make use of LocalDate.
LocalDate stores only date information, since it does not represent an instant, rather a triple of year, month and date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParsingLocalDate {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}
If you do not need to use time of day or time zone, you can parse it by LocalDate.
String str = "01-01-2000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.parse(str, formatter);
Note that for day and time people most of the time would want a ZonedDateTime rather than a LocalDateTime. The name is counter-intuitive; the Local in both LocalDate and LocalDateTime means any locality in general rather than a specific time zone.
In most programming languages, date/time types are simply containers for the amount of time which has passed from a given point in time. They don’t have a format.
In the case of Java (AFAIR), time is measured in milliseconds since the Unix Epoch.
Since it's 2019, there is no excuse not to making use of the java.time APIs (or the ThreeTen backport) and you should avoid using the, now effectively deprecated, older APIs
Parse String to LocalDate
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.parse("08-03-1972", inputFormatter);
Format LocalDate to desired format
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd EEE MMM yyyy");
String value = localDate.format(outputFormatter);
System.out.println(value);
which outputs
08 Wed. Mar. 1972

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.

Categories