How do i format date like this 2019-07-08T10:37:28Z in flutter

7,944

Solution 1

You can use this:

var now = new DateTime.now();
var dateFormatted = DateFormat("yyyy-MM-ddTHH:mm:ss").format(now);

You have to add the "Z" at the end of the String because is a Char used to format the TimeZone.

You can check it there -> https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

Solution 2

You can refer to DateFormat class here https://api.flutter.dev/flutter/intl/DateFormat-class.html It has a constructor where you can put your pattern.

    final format = new DateFormat('yyyy-MM-ddTHH:mm:ssZ','en-US');

Solution 3

It's UTC type of ISO 8601 format datetime.

Below method to parse this date format and return today default if have exception:

String formatDateTimeFromUtc(dynamic time){
  try {
    return new DateFormat("yyyy-MM-dd hh:mm:ss").format(new DateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(time));
  } catch (e){
    return new DateFormat("yyyy-MM-dd hh:mm:ss").format(new DateTime.now());
  }
}
Share:
7,944
Rutvik Gumasana
Author by

Rutvik Gumasana

flutterrun.com

Updated on December 15, 2022

Comments

  • Rutvik Gumasana
    Rutvik Gumasana over 1 year

    I want to format the date like this 2019-07-08T10:37:28Z but I don't know how to do it can anyone help me with this.

    Here is the code for date picker

    final format = new DateFormat.yMMMEd('en-US');
    
    return DateTimeField(
          format: format,
          autocorrect: true,
          autovalidate: false,
          controller: _bspLicenseExpiryDate,
          readOnly: true,
          validator: (date) => date == null ? 'Please enter valid date' : null,
          decoration: InputDecoration(
              labelText: "Expiry Date",
              hintText: "Expiry Date",
              prefixIcon: Icon(
                FontAwesomeIcons.calendar,
                size: 24,
              )),
          onShowPicker: (context, currentValue) {
            return showDatePicker(
              context: context,
              firstDate: DateTime.now(),
              initialDate: currentValue ?? DateTime.now(),
              lastDate: DateTime(2100),
            );
          },
        );