Dates and Times Parsing
Description
Parsing which is handled by a DateTimeFormatter
is to create a date time object from a string.
The same symbols used for formatting are used as parsing string values.
A DateTimeParseException
is thrown if the text cannot be parsed.
It has two methods to provide the error details.
getErrorIndex()
returns the error offset in the text.
getParsedString()
returns the text being parsed.
Both date time related classes and DateTimeFormatter defines methods to parse a string into a datetime object.
parse() method from datetime class
Each datetime class has two overloaded versions of the parse()
.
The return type of the parse()
method is the same as the defining datetime class.
The following code shows how to use parse()
methods
from LocalDate
objects:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/*from w w w . j ava 2 s . c o m*/
public class Main {
public static void main(String[] args) {
LocalDate ld1 = LocalDate.parse("2014-06-10");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate ld2 = LocalDate.parse("06/10/2014", formatter);
System.out.println("ld1: " + ld1);
System.out.println("ld2: " + ld2);
}
}
The code above generates the following result.
parse() from DateTimeFormatter class
DateTimeFormatter
class contains several parse() methods to parse
strings into datetime objects.
Most of them return a TemporalAccessor object that you can query to get the datetime components.
You can pass the TemporalAccessor object to the from() method of the datetime class to get the specific datetime object.
The following code shows how to parse a string in MM/dd/yyyy format using a DateTimeFormatter object to construct a LocalDate:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
/*from ww w . j av a 2s . c om*/
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
TemporalAccessor ta = formatter.parse("06/10/2014");
LocalDate ld = LocalDate.from(ta);
System.out.println(ld);
}
}
The code above generates the following result.
Example
parse() method can take a TemporalQuery to parse the string directly into a specific datetime object.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
// w w w. j a v a2s.co m
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate ld = formatter.parse("06/10/2014", LocalDate::from);
System.out.println(ld);
}
}
The code above generates the following result.