1. String time
In Java, you can use In the package
DateTimeFormatter
Class converts date and time in string format toLocalDateTime
orZonedDateTime
Object.
(I) Use predefined format
import ; import ; public class StringToDateExample { public static void main(String[] args) { String isoDateTime = "2023-10-11T12:34:56"; DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; LocalDateTime dateTime = (isoDateTime, formatter); ("Date and time after parsing: " + dateTime); } }
(II) Custom format
import ; import ; public class CustomStringToDateExample { public static void main(String[] args) { String customDateTime = "2023-10-11 12:34:56"; DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = (customDateTime, formatter); ("Date and time after parsing: " + dateTime); } }
2. Time to string
Format the date and time object into a string, you can useDateTimeFormatter
kind.
(I) Use predefined format
import ; import ; public class DateToStringExample { public static void main(String[] args) { LocalDateTime now = (); DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; String formattedDate = (formatter); ("ISO format date and time: " + formattedDate); } }
(II) Custom format
import ; import ; public class CustomDateToStringExample { public static void main(String[] args) { LocalDateTime now = (); DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss"); String formattedDate = (formatter); ("Custom format date and time: " + formattedDate); } }
3. Process dates in different time zones
You can use when processing dates in different time zonesZonedDateTime
kind.
(I) Date and time of string to use time zone
import ; import ; public class StringToZonedDateTimeExample { public static void main(String[] args) { String zonedDateTimeString = "2023-10-11T12:34:56-04:00"; DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; ZonedDateTime zonedDateTime = (zonedDateTimeString, formatter); ("Resolved Date and Time with Time Zone: " + zonedDateTime); } }
(II) Date and time to string with time zone
import ; import ; public class ZonedDateTimeToStringExample { public static void main(String[] args) { ZonedDateTime now = (); DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss z"); String formattedDate = (formatter); ("Date time string with time zone: " + formattedDate); } }
4. Summary
Java'sThe package provides powerful date and time processing functions through
DateTimeFormatter
It is easy to convert between a datetime object and a string.
This is the introduction to this article about the detailed explanation of the operation of string to time and time to string in Java. For more related contents of Java string to time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!