📜  dart datetime parse - Dart (1)

📅  最后修改于: 2023-12-03 15:00:19.981000             🧑  作者: Mango

Dart DateTime Parse

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.

Syntax

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.

Examples

Let's take a look at a few examples of how to use DateTime.parse() in Dart:

Example 1
String dateString = '2022-01-01 09:00:00';
DateTime date = DateTime.parse(dateString);
print(date);

Output:

2022-01-01 09:00:00.000
Example 2
String dateString = '2022/01/01 09:00:00';
DateTime date = DateTime.parse(dateString.replaceAll('/', '-'));
print(date);

Output:

2022-01-01 09:00:00.000
Example 3
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
Conclusion

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.