Java 17 Recipes


-16. Obtaining Date-Time from a Specified String


Download 3.2 Mb.
Pdf ko'rish
bet86/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   82   83   84   85   86   87   88   89   ...   245
Bog'liq
Java 17 Recipes

4-16. Obtaining Date-Time from a Specified String
 Problem
You want to parse a string into a date-time object.
Chapter 4 Numbers aNd dates


142
 Solution
Utilize the parse() method of a temporal date-time class to parse a string using a 
predefined or custom format. The following lines of code demonstrate how to parse a 
string into a date or date-time object using variations of the parse() method.
public static void parseDateTime(){
// Parse a string to form a Date-Time object
LocalDate ld = LocalDate.parse("2019-12-28");
LocalDateTime ldt = LocalDateTime.parse("2019-12-28T08:44:00");
System.out.println("Parsed Date: " + ld);
System.out.println("Parsed Date-Time: " + ldt);
// Using a different Parser
LocalDate ld2 = LocalDate.parse("2019-12-28",
DateTimeFormatter.ISO_DATE);
System.out.println("Different Parser: " + ld2);
// Custom Parser
String input = "12/28/2019";
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern 
("MM/dd/yyyy");
LocalDate ld3 = LocalDate.parse(input, formatter);
System.out.println("Custom Parsed Date: " + ld3);
} catch (DateTimeParseException ex){
System.out.println("Not parsable: " + ex);
}
}
Here is the result.
Parsed Date: 2019-12-28
Parsed Date-Time: 2019-12-28T08:44
Different Parser: 2019-12-28
Custom Parsed Date: 2019-12-28
Chapter 4 Numbers aNd dates


143
The main is:
public static void main(String[] args) {
parseDateTime();
}
 How It Works
The temporal classes of the Date-Time API include a parse() method, which parses a 
given input string using a specified format. By default, the parse() method format is 
based on the target object’s default DateTimeFormatter. For example, to parse the string 
"2019-01-01", the default LocalDate.parse() method can be called.
LocalDate date = LocalDate.parse("2019-01-01");
However, another DateTimeFormatter can be specified as a second argument to the 
parse() method. DateTimeFormatter is a final class used for formatting and printing 
dates and times. It contains several built-in formatters that can be specified to coerce 
strings into date-time objects. Often, it is necessary to parse strings of text into date-time 
objects. Such tasks are made easy with the parse() method built into many core date- 
time classes.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   82   83   84   85   86   87   88   89   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling