Search code examples
flutterflutter-datetime-picker

DateFormat dateFormat = DateFormat("yyyy-MM-dd"); To Month-Day-Year


DateFormat dateFormat = DateFormat("yyyy-MM-dd"); This line of code will not let me change the DateFormat to ("MM-dd-yyyy") without showing throwing an error in the app, or not displaying correctly.

I just need it to show MONTH-DAY-YEAR, NOT YEAR-MONTH-DAY

Flutter refuses to let me change it. Nobody seems to have an answer for how to change it. I've been looking for two weeks on how to change it with no luck.

Also asked here: Flutter DatePicker change format to MM-DD-YYYY, but none of the answers worked either.

Here's the error being thrown in the app:

enter image description here

EDIT: More Code Context.

The original line was this:

DateFormat dateFormat = DateFormat("yyyy-MM-dd");

DateTime dateTime = dateFormat.parse(ticketModel.date);

dateTime was then getting shown via Text in a container this way:

 child: Text(dateTime.toString().split(' ').first.toString(),
                style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                      letterSpacing: 2.5,
                      color: Colors.white,
                    )),

This is NOT my code, and I am not a Flutter dev. Something is happening in these lines that won't allow MM-dd-yyyy to work properly.

The error is a photo, because it is getting displayed in the app container, not in any sort of terminal. I didn't want any mistakes if I tried copying it to text. I know its frowned upon, this isn't my first rodeo getting scolded on Stackoverflow, but I was desperate here.

My issue was solved for now by following that person's answer below and changing my code to this:

 DateFormat dateFormat = DateFormat("yyyy-MM-dd");

 DateTime fudgeThis = dateFormat.parse(ticketModel.date);

 String dateTime = fudgeThis.showDateInOwnFormat();

Hopefully this edits help someone. Seriously.


Solution

  • let's say I have the DateTime variable

    DateTime ourDateExample = DateTime.now();
    

    you can create your own extension on DateTime to achieve what you want

    extension ShowDataInOwnFormat on DateTime {
      String showDateInOwnFormat() {
      return '$month-$day-$year';
    }}
    

    put this outside of your classes or on a separate file, then call it whenever you want like this :

    ourDateExample.showDateInOwnFormat();
    

    it will return the date as the Month-day-year