📅  最后修改于: 2023-12-03 15:00:19.981000             🧑  作者: Mango
Dart provides a powerful DateTime class, which represents a point in time. When working with dates, it is often necessary to parse strings into DateTime objects. The Dart DateTime Parse function provides a way to do this easily.
The syntax for DateTime.parse() is simple:
DateTime.parse(String input);
Here, input is the string that you want to parse into a DateTime object.
Let's take a look at a few examples of how to use DateTime.parse() in Dart:
String dateString = '2022-01-01 09:00:00';
DateTime date = DateTime.parse(dateString);
print(date);
Output:
2022-01-01 09:00:00.000
String dateString = '2022/01/01 09:00:00';
DateTime date = DateTime.parse(dateString.replaceAll('/', '-'));
print(date);
Output:
2022-01-01 09:00:00.000
String dateString = '01/01/2022 09:00:00 AM';
DateFormat format = DateFormat('MM/dd/yyyy hh:mm:ss a');
DateTime date = format.parse(dateString);
print(date);
Output:
2022-01-01 09:00:00.000
In this article, we have seen how to parse a string into a DateTime object in Dart using the DateTime.parse() function. We have also seen some examples of how to format the input string to match the expected format of the function. With this knowledge, you should be able to easily parse dates in your Dart applications.