Unable to parse string into Java 8 LocalDateTime [duplicate] - java

This question already has answers here:
Is java.time failing to parse fraction-of-second?
(3 answers)
Closed 2 years ago.
Running this gives me the following error, what am I missing ?
public static void main(String[] args) {
DateTimeFormatter _timestampFomatGMT = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalDateTime localDateTime = LocalDateTime.parse("20200331094118137",_timestampFomatGMT);
System.out.println(localDateTime);
}
Gives me the following exception. What am I missing ?
Exception in thread "main" java.time.format.DateTimeParseException: Text '20200331094118137' could not be parsed at index 0
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 cotown.lib.common.util.JavaTimeUtil.main(JavaTimeUtil.java:90)

Java does not accept a plain Date value as DateTime.
Try using LocalDate,
public static void main(String[] args) {
DateTimeFormatter _timestampFomatGMT = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDateTime = LocalDate.parse("20200331",_timestampFomatGMT);
System.out.println(localDateTime);
}
or if you really have to use LocalDateTime, then try
LocalDateTime time = LocalDate.parse("20200331", _timestampFomatGMT).atStartOfDay();
EDIT
there was a bug for this already raised https://bugs.openjdk.java.net/browse/JDK-8031085.
It is fixed in JDK 9.

You cannot parse a date-only String into a LocalDateTime without passing a time value in addition.
What you can do is use a date-only class like LocalDate similar to your code:
public static void main(String[] args) {
DateTimeFormatter _timestampFomatGMT = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDate = LocalDate.parse("20200331",_timestampFomatGMT);
System.out.println(localDate);
}
That would simply output
2020-03-31
If you really need to have a LocalDateTime and the String to be parsed cannot be adjusted to include time, then pass an additional time of 0 hours and minutes with an intermediate operation like this (but keep in mind that the output will include the time information as well):
public static void main(String[] args) {
DateTimeFormatter _timestampFomatGMT = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDate = LocalDate.parse("20200331",_timestampFomatGMT);
LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.of(0, 0));
System.out.println(localDateTime);
}
Or use LocalDateTime time = LocalDate.parse("20200331", _timestampFomatGMT).atStartOfDay(); as suggested by #Shubham.
Output would be:
2020-03-31T00:00
For outputting the date only, change the last line of the last example to
System.out.println(localDateTime.format(DateTimeFormatter.ISO_DATE));
which will only output the date part of the LocalDateTime in an ISO representation:
2020-03-31
EDIT
Targeting your latest question update, this might help:
public static void main(String[] args) {
DateTimeFormatter timestampFomatGMT = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalDateTime localDateTime = LocalDateTime.parse("20200331094118137", timestampFomatGMT);
System.out.println(localDateTime);
}
Output:
2020-03-31T09:41:18.137

Related

How to convert 2022-08-16T06:25:00.000 to HH:mm

I'm trying to convert date from API "2022-08-16T06:25:00.000" to HH:mm (6:25) but getting DateTimeParseException.
My code: ZonedDateTime.parse(it.time[0], DateTimeFormatter.ofPattern("HH:mm"))
"time": [
"2022-08-16T06:25:00.000",
"2022-08-16T07:40:00.000"
],
String dateTimeStr = "2022-08-16T06:25:00.000";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm");
String time = dateTime.format(fmt);
System.out.println(time);
or, if you want to use the time as an instance of LocalTime, you can get it by dateTime.toLocalTime()
You don't need to define any DateTimeFormatter in this situation.
use a LocalDateTime because the input String does not hold any information about the zone
don't use a DateTimeFormatter for parsing that only parses hour of day and minutes of hour, the String to be parsed just contains more information
Here's an example without any DateTimeFormatter explicitly defined (but it will use default ones for parsing, at least):
public static void main(String[] args) {
// example input
String fromApi = "2022-08-16T06:25:00.000";
// parse it to a LocalDateTime because there's no zone in the String
LocalDateTime localDateTime = LocalDateTime.parse(fromApi);
// extract the time-of-day part
LocalTime localTime = localDateTime.toLocalTime();
// and print its toString() implicitly
System.out.println(localTime);
}
Output: 06:25
The above code will produce output of the pattern HH:mm, which will have leading zeros at hours of day to always have a two-digit representation.
If you insist on single-digit hours of day, you will have to prepare a DateTimeFormatter, like in this alternative example:
public static void main(String[] args) {
// example input
String fromApi = "2022-08-16T06:25:00.000";
// parse it to a LocalDateTime because there's no zone in the String
LocalDateTime localDateTime = LocalDateTime.parse(fromApi);
// extract the time-of-day part
LocalTime localTime = localDateTime.toLocalTime();
// prepare a DateTimeFormatter that formats single-digit hours of day
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm");
// print the LocalTime formatted by that DateTimeFormatter
System.out.println(localTime.format(dtf));
}
Output this time: 6:25
The other answers use Java. Since you've added a [kotlin] tag, here is a Kotlin-based answer for the sake of completeness. In order to make it different to the Java answers, I'm using kotlinx.datetime, which is still at the experimental stage at version 0.4.0.
import kotlinx.datetime.LocalDateTime
fun main() {
println(LocalDateTime.parse("2022-08-16T06:25:00.000").time) // prints "06:25"
// If you want "6:25" you can format it yourself:
println(with(LocalDateTime.parse("2022-08-16T06:25:00.000")) {
"$hour:$minute"
})
}
How about different approach
String dateTimeStr = "2022-08-16T06:25:00.000";
Matcher m=Pattern.of("T(\\d{2}:\\d{2}):").matcher(dateTimeStr);
m.find();
System.out.println(m.group(1);; //should print 06:25
And yet another "alternative" answer. It relies on the fact that in an ISO-compliant date-time format, the time starts in the 11th position.
private static final int ISO_TIME_POS = 11;
....
String dateTimeStr = "2022-08-16T06:25:00.000";
String timeStr = dateTimeStr.substring(ISO_TIME_POS, ISO_TIME_POS + 5);
System.out.println(timeStr); // prints "06:25"

Regarding date format in java [duplicate]

This question already has answers here:
Java SimpleDateFormat Timezone offset with minute separated by colon
(2 answers)
Closed 2 years ago.
public class DatePgm {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+'SS:SZ");
Date date1 = sdf.parse("2020-07-26T18:52:24+05:30");
System.out.println("DATE="+sdf.format(date1));
}
}
Can any one help me to print the exact date and time format "2020-07-26T18:52:24+05:30"
tl;dr ⇒ java.time.OffsetDateTime
In this case, you don't really need to define a format/formatter yourself. The default DateTimeFormatter of an OffsetDateTime (which appears suitable here) is able to parse (and print/format) your example String. You can do it as follows:
public static void main(String[] args) {
// your example datetime String
String datetime = "2020-07-26T18:52:24+05:30";
// parse the String to an OffsetDateTime using the default formatter
OffsetDateTime odt = OffsetDateTime.parse(datetime);
// and print the OffsetDateTime using its default formatter
System.out.println("DATE=" + odt);
}
the output is
DATE=2020-07-26T18:52:24+05:30
Use Instant instead of Date. Instant supports date time with zone
Instant date1 = Instant.parse("2020-07-26T18:52:24+05:30");
System.out.println("DATE= " + date1);
You can try following,
String string = "2020-07-26T18:52:24+05:30";
OffsetDateTime odt = OffsetDateTime.parse( string );
System.out.println(odt);
You can use Calendar to get the date:
String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+'SS:SZ").format(Calendar.getInstance().getTime());
I think you should use LocalDatetIme, from java 8. A very good example for most of the formats are available here
With SimpleDateFormat you have to set the timzone(Asia/Colombo is +05:30):
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date1 = sdf.parse("2020-07-26T18:52:24+05:30");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
System.out.println("DATE="+sdf.format(date1));
Output:
DATE=2020-07-26T18:52:24+05:30

How to convert 2017-08-01T16:00:00-04:00 to timestamp in Java?

I am looking to convert the date from default Date format to timestamp in Java.
I tried the following code, but it doesn't work:
String string = "2017-08-01T16:00:00-04:00";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-mm:ss");
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
java.time.format.DateTimeParseException: Text
'2017-08-01T16:00:00-04:00' could not be parsed at index 20
at
java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
Don't use a LocalDate for a String that
contains information about the time of day, wich would have required a LocalDateTime and
contains an offset, wich cannot be considered by a LocalDateTime.
Instead, use an OffsetDateTime:
public static void main(String[] args) {
String string = "2017-08-01T16:00:00-04:00";
OffsetDateTime odt = OffsetDateTime.parse(string);
System.out.println(odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
Output:
2017-08-01T16:00:00-04:00
In addition, your pattern in DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-mm:ss"); has serious flaws, like duplicate items.
You can of course print the result using a pattern different from the input (which complies with the ISO 8601 standard):
public static void main(String[] args) {
String string = "2017-08-01T16:00:00-04:00";
OffsetDateTime odt = OffsetDateTime.parse(string);
System.out.println(odt.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss Z")));
}
Output this time:
01.08.2017 16:00:00 -0400

Why does this date parsing fail? [duplicate]

This question already has answers here:
Is java.time failing to parse fraction-of-second?
(3 answers)
Closed 5 years ago.
I'm trying to convert a string into a LocalDateTime object.
#Test
public void testDateFormat() {
String date = "20171205014657111";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalDateTime dt = LocalDateTime.parse(date, formatter);
}
I would expect this test to pass.
I get the following error:
java.time.format.DateTimeParseException: Text '20171205014657111' could not be parsed at index 0
Looks like I may have run across this bug: https://bugs.openjdk.java.net/browse/JDK-8031085 as it corresponds to the JVM version I'm using. The workaround in the comments fixes the issue for me:
#Test
public void testDateFormat() {
String date = "20171205014657111";
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("yyyyMMddHHmmss")
.appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter();
LocalDateTime dt = LocalDateTime.parse(date, dtf);
}

iso date and time not giving in the required format

what format should i use to get required output
for input "2016-04-01T16:23:19.8995" o/p=2016-04-01T16:23:19.900 therefore .8995 rounded off to .900 in the output
3.similarly for input "2016-04-01T16:23:19.9995" expected output is 2016-04-01T16:23:20.000 not getting expected output
public class Date {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSS");
System.out.println(sdf.parse("2016-04-01T16:23:19.9995"));
}
}
S means millisecond no matter how many S you use.
If you want this behaviour, I suggest you
parse that portion yourself or
use JSR 310 which can handle nanoseconds in timestamps.
Using the DateTime library in Java 8.
String dateTime = "2016-04-01T16:23:19.8995";
LocalDateTime localDateTime = LocalDateTime.parse(dateTime);
System.out.println(localDateTime);
prints
2016-04-01T16:23:19.899500
if you want to round it you can do.
LocalDateTime inMillis = localDateTime.plusNanos(500_000).truncatedTo(ChronoUnit.MILLIS);
System.out.println(inMillis);
prints
2016-04-01T16:23:19.900
In Java 8, you can use java.time.LocalDateTime.
LocalDateTime time = LocalDateTime.parse("2016-04-01T16:23:19.9995");
System.out.println(time); //gives 2016-04-01T16:23:19.999500 as output
LocalDateTime should give you at-least the desired format.
And as Peter answered, S is milliseconds no matter how many S you use.

Categories

Resources