I would like to have my DateTime to always save as 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 me print statements and error to see what is successful and 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>
DateTimestring at all; you instead tried to cast it (i.e., pretend that theStringis aDateTimeobject, which it isn't). If you want to actually parse it, see convert datetime string to datetime object in dart? - jamesdlinDateTime.parsehandles only a small set of date/time formats. Since you formatted theDateTimeto a string usingDateFormat, you should parse it back withDateFormattoo:DateFormat.yMMMd().parse(formattedDate). - jamesdlinDateTimeby definition stores both a date and a time. You're free to ignore the time portion, but you will need to useDateFormatwhenever you want to convert it to aString(or back). You could make your ownDateclass that internally stores aDateTimeand whosetoString()method usesDateFormat. - jamesdlin