skip to Main Content

I want to display the string of datetime 2023-01-01 11:59:59:0000 in a readable manner like January 01, 2023 11:59:59 AM

I do have a controllers for both DateFrom to DateTo and this accepts DateTime values. So once the controllers have the value I want them to be displayed January 01,2023 11:59:59AM instead of the raw DateTime format.

I have this error Trying to read MMMM from at 0

This is my first attempt on converting the display of the value

 textContainer("Date From: ",
              "${(DateFormat('MMMM d, y', 'en_US').parse(_couponDateFromCtrlr.text))}"),
 textContainer("Date From: ",
              "${(DateFormat('MMMM d, y', 'en_US').parse(_couponDateFromCtrlr.text))}")

and this is my second attempt and it gives me invalid date format error

_couponDateFromCtrlr.text != null
              ? textContainer("Date From: ",
                  "${(DateFormat('MMMM d, y', 'en_US').parse(_couponDateFromCtrlr.text))}")
              : const Text("No Date From Selected"),
          _couponDateToCtrlr.text != null
              ? textContainer("Date To: ",
                  "${(DateFormat('MMMM d, y', 'en_US').parse(_couponDateToCtrlr.text))}")
              : const Text("No Date To Selected")

and this is the ui of it when displaying.

Here is the Date Time I wanna change and I want to change it to April 26, 2023 3:58PM

2

Answers


  1. Here is an example of how to get DateTime from the string format of 2023-01-01 11:59:59:0000 and then parse it to the string in this format January 01,2023 11:59:59AM:

    final date = DateFormat('yyyy-mm-dd hh:mm:ss', 'en_US')
                .parse("2023-01-01 11:59:59:0000"); // string from your text controller
    final string = DateFormat('MMMM d, y hh:mm:ss a', 'en_US').format(date); // result --> January 01,2023 11:59:59AM
    

    If you get DateTime format from your _couponDateFromCtrlr you can skip the first part.

    Login or Signup to reply.
  2. Just pass the DateTime value to the following function:

    DateFormat.yMMMMd().format(value)

    This should return you the required format.
    Refer the cheatsheet available here for your date format needs.

    DateFormat Flutter: 2 Ways to Master DateTime Format

    Happy coding 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search