I would like to have my DateTime always save in the following format: yMMMd
I.e. March 30, 2021
Problem:
When I format my DateTime, it formats as a String. When I try to parse this back into DateTime I get errors and no success.
I'm having issues chasing down a good solution to doing this.
Is this possible or do I have to settle for saving as a String?
EDIT
Tried everything that has been recommended and I tried many other methods which didn't work either. I wonder if the Intl package date format has trouble being parsed back to DateTime? That could be my issue. Anyone?
Please have a look at my print statements and errors to see what is successful and what isn't.
My date selector where I'm trying this:
Future<void> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101));
if (picked != null)
setState(() {
print('------ Picked date: $picked');
var dateString = '';
final formattedDate = DateFormat.yMMMd().format(picked);
var parsedDate = DateTime.parse(formattedDate); // Does not work...
print('------- Parsed date: $parsedDate');
dateString = formattedDate;
print('------ String date: $dateString');
expenseDate = formattedDate as DateTime;
print('------ Formatted date: ${formattedDate.toString()}');
});
}
Error:
flutter: ------ Picked date: 2021-03-31 00:00:00.000
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: FormatException: Invalid date format
Mar 31, 2021
#0 DateTime.parse (dart:core/date_time.dart:322:7)
#1 _AddExpenseButtonState._selectDate.<anonymous closure> (package:fp_provider_demo_one/widgets/add_expense_button.dart:48:35)
#2 State.setState (package:flutter/src/widgets/framework.dart:1267:30)
#3 _AddExpenseButtonState._selectDate (package:fp_provider_demo_one/widgets/add_expense_button.dart:44:7)
<asynchronous suspension>