Bisma Frühling
Bisma Frühling

Reputation: 774

Dart - Convert time from dd/MM/YYYY to YYYY-MM-dd

How to convert a date from dd/MM/YYYY to YYYY-MM-dd

Example: convert from 08/11/2019 to 2019-11-08

I tried the following code but got the

Invalid date format 08/11/2019 exception

import 'package:intl/intl.dart';

DateFormat('YYYY-MM-dd').format(DateTime.parse('08.11.2019'));

Upvotes: 10

Views: 16096

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267714

var inputFormat = DateFormat('dd/MM/yyyy');
var date1 = inputFormat.parse('18/08/2019');

var outputFormat = DateFormat('yyyy-MM-dd');
var date2 = outputFormat.format(date1); // 2019-08-18

Or you can use String

var date2String = outputFormat.format(date1); // "2019-08-18"

Upvotes: 26

Jama Mohamed
Jama Mohamed

Reputation: 3405

Try using this package, Jiffy. It is inspired by momentjs.

This can be solved in one line

var dateTime = Jiffy("18/08/2019", "dd/MM/yyyy").format("yyyy-MM-dd"); // 2019-08-18

You can also format it with default formats

var dateTime = Jiffy("18/08/2019", "dd/MM/yyyy").yMMMMd; // August 18, 2019

Upvotes: 1

Related Questions