This question already has answers here:
Is java.time failing to parse fraction-of-second?
(3 answers)
Closed 1 year ago.
Hello I try parse String 20110330174824917 to OffsetDateTime using DateTimeFormatter so
public static void main(String[] args) {
// System.out.println(OffsetDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
System.out.println(LocalDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
}
but I get
Exception in thread "main" java.time.format.DateTimeParseException: Text '20110330174824917' could not be parsed, unparsed text found at index 8
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
Hey guys it looks like this problem is related with java 8
https://bugs.openjdk.java.net/browse/JDK-8031085
Thank you all for help
DateTimeFormatter#withZone
Your date-time string does not have timezone information and therefore, in order to parse it into OffsetDateTime, you need to pass the timezone information explicitly. You can use DateTimeFormatter#withZone to parse the date-time string into ZonedDateTime which you can convert to OffsetDateTime using ZonedDateTime#toOffsetDateTime.
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "20110330174824917";
// Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
OffsetDateTime odt = ZonedDateTime.parse(strDateTime, dtf)
.toOffsetDateTime();
System.out.println(odt);
}
}
Output:
2011-03-30T17:48:24.917+01:00
You can define the used Zone for the Formatter and concatenate the input string with the correct Zone Offset
// note the added Z at the end of the pattern for the offset
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSZ").withZone(ZoneId.of("UTC"));
OffsetDateTime dateTime = OffsetDateTime.parse("20110330174824917" + "+0000", formatter);
Related
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.
I have an API for JSON parsing which requires a DateTimeFormatter instance in order to parse date time strings to OffsetDateTime. However I always get an exception Unable to obtain ZoneOffset from TemporalAccessor: {},ISO resolved to 2021-08-17T13:26:49 of type java.time.format.Parsed
The API uses OffsetDateTime.parse(String, DateFormatter).
// DateTimeFormatter instance to be provided to the API
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
// this is how the API uses the DateTimeFormatter instance
OffsetDateTime dateTime = OffsetDateTime.parse("20210817132649", formatter);
How do I have to create the DateTimeFormatter in order to deliver a ZoneOffset, so that the API is able to parse the DateTime correctly. The ZoneOffset may be UTC.
Update
I understood from you that you are using the API as follows:
apiClient.getJSON().setOffsetDateTimeFormat(DateTimeFormatter);
and you do not have a parameter to pass timezone information. In this case, you can use DateTimeFormatter#withZone as shown below:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
OffsetDateTime odt = OffsetDateTime.parse("20210817132649", formatter);
System.out.println(odt);
}
}
Output:
2021-08-17T13:26:49Z
ONLINE DEMO
i.e. now, your call will be:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
apiClient.getJSON().setOffsetDateTimeFormat(formatter);
Original answer
Your date-time string does not have a timezone offset. Parse it into a LocalDateTime and then apply the offset to it.
Demo:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH);
OffsetDateTime odt = LocalDateTime.parse("20210817132649", formatter)
.atOffset(ZoneOffset.UTC);
System.out.println(odt);
}
}
Output:
2021-08-17T13:26:49Z
ONLINE DEMO
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours). You can specify a different timezone offset (e.g. ZoneOffset.of("+05:30")) as per your requirement.
In case you have ZoneId available
If you have ZoneId available, you should parse the given date-time string into a LocalDateTime and then apply the ZoneId to it to get a ZonedDateTime from which you can always obtain an OffsetDateTime. The best thing about a ZonedDateTime is that it has been designed to adjust the timezone offset automatically whereas an OffsetDateTime is used to represent a fixed timezone offset.
Demo:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH);
ZonedDateTime zdt = LocalDateTime.parse("20210817132649", formatter)
.atZone(ZoneId.of("Etc/UTC"));
OffsetDateTime odt = zdt.toOffsetDateTime();
System.out.println(odt);
}
}
Output:
2021-08-17T13:26:49Z
ONLINE DEMO
You can specify a different ZoneId(e.g. ZoneId.of("Asia/Kolkata")) as per your requirement.
Learn more about the modern Date-Time API* from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.
Well, the string you passed in does not contain zone information, while an OffsetDateTime requires zone information.
So you'll have to set a value for it.
You could use the DateTimeFormatterBuilder class, which then can be instructed to use some default value if a field is missing from the parsed information:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.appendPattern("yyyyMMddHHmmss")
.toFormatter(Locale.ROOT);
You could also directly set an implied zone to the DateTimeFormatter:
DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.UTC);
Better use a ZonedDateTime - the difference being the Day Saving Time, and countries on with the same zone offset. Maybe using the default ZoneId.
I having a hard time trying to format a string time into MM:DD::YY and only time. From an IP i getting the time in the following format
2021-09-10T00:37:42Z
and I'm want to display the date and time in:
09/08/2021
Time
09:50PM
Parse the given string into OffsetDateTime and then get LocalDate and LocalTime parts out of it.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021-09-10T00:37:42Z";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
LocalTime time = odt.toLocalTime();
LocalDate date = odt.toLocalDate();
System.out.println(time);
System.out.println(date);
// #########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formattedDateString = date.format(dtfDate);
System.out.println(formattedDateString);
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime);
System.out.println(formattedTimeString);
}
}
Output:
00:37:42
2021-09-10
09/10/2021
12:37 AM
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
Update based on an important comment by Ole V.V.:
The OP — or their user — may want the date and time in their own time
zone.
In order to get the date and time parts in a specific timezone e.g. America/Los_Angeles, you should parse the given date-time string into ZonedDateTime and convert the same to the ZonedDateTime of the specific timezone using ZonedDateTime#withZoneSameInstant. Rest of the things will remain same as the original answer.
Demo:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021-09-10T00:37:42Z";
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime);
ZonedDateTime zdtLosAngeles = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
LocalTime time = zdtLosAngeles.toLocalTime();
LocalDate date = zdtLosAngeles.toLocalDate();
System.out.println(time);
System.out.println(date);
// #########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formattedDateString = date.format(dtfDate);
System.out.println(formattedDateString);
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime);
System.out.println(formattedTimeString);
}
}
Output:
17:37:42
2021-09-09
09/09/2021
05:37 PM
ONLINE DEMO
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
This question already has answers here:
Unable to obtain ZonedDateTime from TemporalAccessor using DateTimeFormatter and ZonedDateTime in Java 8
(5 answers)
Closed 1 year ago.
In the following code:
ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String zdtString = FORMATTER.format(zdt);
System.out.println(zdtString);
you will see it prints out the current date in yyyy-DD-mm format. Since this question was posted on July 17, 2021, it printed:
2021-07-17
But now I would like to change the date to something different (like 1994-03-24).
So I tried:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime zdt2 = ZonedDateTime.parse("1994-03-24", FORMATTER);
String zdtString = FORMATTER.format(zdt2);
System.out.println(zdtString);
But then I get the following Exception:
Exception in thread "main" java.time.format.DateTimeParseException: Text '1994-03-24' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1994-03-24 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at javaapplication5.JavaApplication5.main(JavaApplication5.java:48)
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1994-03-24 of type java.time.format.Parsed
at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 2 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: {},ISO resolved to 1994-03-24 of type java.time.format.Parsed
at java.time.ZoneId.from(ZoneId.java:466)
at java.time.ZonedDateTime.from(ZonedDateTime.java:553)
... 4 more
How do I set my own dates to something other than current date?
1994-03-24 does not have timezone information and therefore it can not be parsed into ZonedDateTime until you provide the timezone information. Also, you will need to default the time units.
1994-03-24 can be directly parsed into LocalDate as the modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
System.out.println(LocalDate.parse("1994-03-24"));
}
}
Output:
1994-03-24
ONLINE DEMO
Demo of parsing with default time unit and a specific timezone:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("u-M-d[ H]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter(Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse("1994-03-24", dtf);
System.out.println(zdt);
}
}
Output:
1994-03-24T00:00Z[Europe/London]
ONLINE DEMO
Note: ZoneId.systemDefault() returns the JVM's ZoneId. Replace it with the applicable ZoneId e.g. ZoneId.of("America/New_York"). Also, notice the optional pattern inside the square bracket which has been defaulted to 0.
Learn more about the modern Date-Time API from Trail: Date Time.
This question already has answers here:
Convert Json date to java date
(3 answers)
How can I convert Json Date to Java Date
(6 answers)
Closed 2 years ago.
so I have this problem converting Integer DateTime format to normal DateTime format in Java.
I have this this variable int DateTime, for example it is : "/Date(1484956800000)/" . And i am trying to convert it to normal date time and show it to the screen ...
I tried like this..
String dateAsText = new SimpleDateFormat("MM-dd HH:mm")
.format(new Date(Integer.parseInt(deals.getDate_time()) * 1000L));
// setting my textView with the string dateAsText
holder.Time.setText(dateAsText);
I suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Obtain an instance of Instant using milliseconds from the epoch of
// 1970-01-01T00:00:00Z
Instant instant = Instant.ofEpochMilli(1484956800000L);
System.out.println(instant);
// Specify the time-zone
ZoneId myTimeZone = ZoneId.of("Europe/London");
// Obtain ZonedDateTime out of Instant
ZonedDateTime zdt = instant.atZone(myTimeZone);
// Obtain LocalDateTime out of ZonedDateTime
// Note that LocalDateTime throws away the important information of time-zone
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// Custom format
String dateAsText = ldt.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
System.out.println(dateAsText);
}
}
Output:
2017-01-21T00:00:00Z
2017-01-21T00:00
01-21 00:00
If you still want to use the poorly designed legacy java.util.Date, you can do it as follows:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date(1484956800000L);
System.out.println(date);
// Custom format
String dateAsText = new SimpleDateFormat("MM-dd HH:mm").format(date);
System.out.println(dateAsText);
}
}
Output:
Sat Jan 21 00:00:00 GMT 2017
01-21 00:00