Not able to parse String to Java Date - java

I have a string "2017-01-03T02:20:52+00:00" I want to convert into a LocalDateTime.
I tried the code below
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
String date = "2009-07-16T19:20:30-05:00";
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime dateTime = LocalDateTime.parse(date, inputFormatter);
System.out.println(dateTime);
}
}
I tried various pattern but every time I am getting below error:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2009-07-16T19:20:30-05:00' could not be parsed at index 19
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at HelloWorld.main(HelloWorld.java:11)

A single Z does not allow : in the timezone. Use ZZZZZ (five Z) for the extended format.

The format of your date String is incorrect
Change it like so:
String date = "2009-07-16T19:20:30-0500";
Note the change before the timezone.

If you want to keep your date format, you can use this pattern:
String pattern = "yyyy-MM-dd'T'HH:mm:ssXXX";

try this:
String date = "2009-07-16T19:20:30-0500";
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
or
String date = "2009-07-16T19:20:30-05:00";
String pattern = "yyyy-MM-dd'T'HH:mm:ssz";

Related

Trying to convert from 2023-01-11 18:27:59UTC-06:00 to 2023-01-12T00:27:59.000Z -- parsing fails

I have string date format like below
2023-01-11 18:27:59UTC-06:00
need to convert to like 2023-01-12T00:27:59.000Z (in UTC zone)
I tried the below. I am getting exception Exception in thread "main" java.time.format.DateTimeParseException: Text '2023-01-09 23:56:59UTC-05:30' could not be parsed at index 10. The exception is coming from this line:
LocalDateTime labelTime = LocalDateTime.parse(dateUTC, DateTimeFormatter.ofPattern(INPUT_FORMAT));
My short code example:
String dateUTC="2023-01-09 23:56:59UTC-05:30";
final String INPUT_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
final String OUTPUT_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX";
final DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(OUTPUT_FORMAT);
LocalDateTime labelTime = LocalDateTime.parse(dateUTC, DateTimeFormatter.ofPattern(INPUT_FORMAT));
ZoneId utcZoneId = ZoneId.of("UTC");
ZonedDateTime zdt = labelTime.atZone(utcZoneId);
System.out.println("OUT PUT Format"+dtf2.format(zdt));
Use the pattern, uuuu-MM-dd HH:mm:ss'UTC'XXX to parse the given date-time string into an OffsetDateTime and convert the result into another OffsetDateTime with ZoneOffset.UTC using OffsetDateTime#withOffsetSameInstant.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss'UTC'XXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2023-01-11 18:27:59UTC-06:00", parser)
.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odt);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
String formatted = odt.format(formatter);
System.out.println(formatted);
}
}
Output:
2023-01-12T00:27:59Z
2023-01-12T00:27:59.000Z
ONLINE DEMO
Note: Here, you can use y instead of u but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.

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

Convert String to LocalDateTime Java 8

I'm trying to convert the following String into a LocalDateTime:
String dateStr = "2020-08-17T10:11:16.908732";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnn");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
But I'm hitting the following error:
java.time.format.DateTimeParseException: Text '2020-08-17T10:11:16.908732' could not be parsed at index 10
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
Can anyone please help to advise how I should be correctly formatting the string into a LocalDateTime?
Many thanks
You don't need to specify a DateTimeFormatter in this case because the default one will be used if you don't pass one at all:
public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
// the following uses the DateTimeFormatter.ISO_LOCAL_DATE_TIME implicitly
LocalDateTime dateTime = LocalDateTime.parse(dateStr);
System.out.println(dateTime);
}
That code will output 2020-08-17T10:11:16.908732.
If you are insisting on using a custom DateTimeFormatter, consider the T by single-quoting it in the pattern and don't use nanosecond parsing (n) for parsing fractions of second (S), the result might be wrong otherwise.
Do it like this:
public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
System.out.println(dateTime);
}
with the same output as above.
Note:
The result of using the pattern "yyyy-MM-dd'T'HH:mm:ss.nnnnnn" would not be equal to the parsed String, instead, it would be
2020-08-17T10:11:16.000908732
For your given DateTime string pattern should be updated "yyyy-MM-dd'T'HH:mm:ss.nnnnnn".
So the code should be like :
String dateStr = "2020-08-17T10:11:16.908732";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.nnnnnn");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
For more details around it you can refer JavaDoc.
Along that in your given input DateTime it's using 6 digits, so it can't be nano seconds. Because nano is 1/1000000000. So it will have at least 9 digits. So the correct format rather should be second fraction with 6 digits as "yyyy-MM-dd'T'HH:mm:ss.SSSSSS".
End Results comparison:
With Pattern : "yyyy-MM-dd'T'HH:mm:ss.nnnnnn"
System.out.println(LocalDateTime.parse("2020-08-17T10:11:16.908732", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.nnnnnn")));
Output : 2020-08-7T10:11:16.000908732
With Pattern : "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
System.out.println(LocalDateTime.parse("2020-08-17T10:11:16.908732", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS")));
Output : 2020-08-7T10:11:16.908732

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.

Java SimpleDateFormat.parse throws : Unparseable date: "2015-10-06T08:00:00+00:00" (at offset 10)

Hello i have the following string with datetime:
public static String nextOccurenceString = "2015-10-06T08:00:00+00:00";
And i want to parse and format string into the following format by following pattern:
public static String pattern = "yyyy-MM-dd HH:mm:ss";
But when i try to call method which should parse the date string into date object i always get exception:
Unparseable date: "2015-10-06T08:00:00+00:00" (at offset 10)
Method is following:
public static void convertStringToDate(String dateString) {
try {
SimpleDateFormat sdf;
sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
Date test = sdf.parse(nextOccurenceString);
Logger.d(test.toString());
} catch (Exception e) {
Logger.e(e.getMessage());
}
}
And I'm using the standard formatting and parsing class:
http://developer.android.com/reference/java/text/SimpleDateFormat.html
How can i solve it please? Should replace something in nextOccurenceString or can i work with string in format like:
"2015-10-06T08:00:00+00:00" ?
Many thanks for any advice.
Your pattern is wrong. It must be:
public static String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
For more information read the javadoc of SimpleDateFormat
The correct pattern for your string is yyyy-MM-dd'T'HH:mm:ssZ (ISO 8601) and not yyyy-MM-dd HH:mm:ss

Categories