Dart:
Parsing a date from a string
How to:
Dart’s core library simplifies date parsing through the DateTime
class. For straightforward cases where you know the format of the date string, you can use DateTime.parse()
method. However, for more complex scenarios or when dealing with multiple formats, the intl
package, specifically the DateFormat
class, becomes invaluable.
Using Dart Core Library:
void main() {
// Using DateTime.parse()
var dateString = "2023-10-31";
var parsedDate = DateTime.parse(dateString);
print(parsedDate); // 2023-10-31 00:00:00.000
}
Using intl
Package:
First, add the intl
package to your pubspec.yaml
file:
dependencies:
intl: ^0.17.0
Then, import the package and use DateFormat
for parsing:
import 'package:intl/intl.dart';
void main() {
var dateString = "October 31, 2023";
var dateFormat = DateFormat("MMMM dd, yyyy");
var parsedDate = dateFormat.parse(dateString);
print(parsedDate); // 2023-10-31 00:00:00.000
}
The intl
package offers robust options for date parsing, allowing handling of various international date formats seamlessly.