6

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),
        );
      },
    );
Rutvik Gumasana
  • 1,458
  • 11
  • 42
  • 66
  • 2
    `DateTime` has a `.toIso8601String()` method, but it does print the fractional seconds. Try `print(DateTime.now().toUtc().toIso8601String());` – Richard Heap Nov 12 '19 at 14:18

3 Answers3

12

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

Caffo17
  • 513
  • 2
  • 10
  • 6
    You can/should quote the non-format characters - this allows you to add the Z. `var dateFormatted = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(DateTime.now());` – Richard Heap Nov 12 '19 at 14:14
  • @Caffo17 "Z" indicates that the time represented is in UTC! – funder7 Jan 01 '21 at 22:13
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');
Debasmita Sarkar
  • 6,367
  • 1
  • 9
  • 9
1

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());
  }
}
Doan Bui
  • 3,572
  • 25
  • 36