Never hardcode the standard timezone text like UTC
, GMT
etc.
Never hardcode the standard timezone text like UTC
, GMT
etc. which DateTimeFormatter
is already capable of handling in the best way.
Parse the given Date-Time string using the pattern, uuuu-MM-dd HH:mm:ss VV
into a TemporalAccessor
from which you can get the Instant
as well as the LocalDateTime
.
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021-09-17 11:48:06 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss VV", Locale.ENGLISH);
TemporalAccessor temporalAccessor = dtf.parse(strDateTime);
Instant instant = Instant.from(temporalAccessor);
LocalDateTime ldt = LocalDateTime.from(temporalAccessor);
System.out.println(instant);
System.out.println(ldt);
}
}
Output:
2021-09-17T11:48:06Z
2021-09-17T11:48:06
ONLINE DEMO
Alternatively:
Parse the given Date-Time string using the pattern, uuuu-MM-dd HH:mm:ss VV
into a ZonedDateTime
from which you can get the Instant
as well as the LocalDateTime
.
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
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-17 11:48:06 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss VV", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
Instant instant = Instant.from(zdt);
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(zdt);
System.out.println(instant);
System.out.println(ldt);
}
}
Output:
2021-09-17T11:48:06Z[UTC]
2021-09-17T11:48:06Z
2021-09-17T11:48:06
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* 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.