Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
时间: 2024-04-23 20:28:20 浏览: 127
If you want to parse the text from the beginning of the string to produce a date, you can use the `parse()` method of the `SimpleDateFormat` class along with the `setLenient()` method set to `false`. By default, the `setLenient()` method is set to `true`, which allows for lenient parsing of dates. When set to `false`, it requires strict parsing.
Here's an example:
```java
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample {
public static void main(String[] args) {
String dateString = "2022-01-01 12:34:56";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
dateFormat.setLenient(false);
Date date = dateFormat.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
In the above example, we set `setLenient(false)` to enforce strict parsing. The provided date string includes a time component, but since we only specify the format as "yyyy-MM-dd", the time component will not be considered. The parsing will stop at the first encountered invalid character or when the format pattern is satisfied.
Note that if the provided string contains additional characters after the date portion, they will be ignored during parsing.
I hope this helps! Let me know if you have any further questions.
阅读全文