DateTime formatting is a common utility in any programing language. In this tutorial, we are building a plug-and-play solution for the time-saving purpose and also demonstrate different-different date formatting and parsing method.
1. Install Package
Add this to your package’s pubspec.yaml
file:
dependencies:
intl: ^0.15.8
The latest version of the library can be found here. This package provides date formatting and parsing facilities. This library also defines the DateFormat, NumberFormat, and BidiFormatter classes.
import 'package:intl/intl.dart';
2. Get the Current Timestamp
To get the current timestamp you can use the millisecondsSinceEpoch of DateTime.now().
var now = new DateTime.now();
print(now.millisecondsSinceEpoch); // => 1555837118231
DateTime comes with some useful constant values for days and months:
print(now.year); // => 2019
print(now.month); // => 4
print(now.day); // => 21
print(now.weekday); // => 7
print(now.hour); // => 14
3. Get the current date
It’s a simple one-line code for get the current Date in any format. You can use DateFormat class to extract date.
print(new DateFormat("dd-MM-yyyy").format(now)); // => 21-04-2019
4. Get the Current time
It’s one line code to get the current time from the DateTime object. You can use DateFormat class to extract time.
print(new DateFormat("H:m:s").format(now)); // => 14:40:25
5. Format Date
To format a DateTime, create a DateFormat instance. These can be created using an explicit pattern. For details on the supported skeletons and patterns see DateFormat.
print(new DateFormat("yyyy-MM-dd hh:mm:ss").format(now)); // => 2019-04-21 02:38:40
print(new DateFormat("dd-MM-yyyy hh:mm:ss").format(now)); // => 21-04-2019 02:40:25
6. DateTime from string or Parsing DateTime
DateFormat class is for formatting and parsing dates in a locale-sensitive manner.
print(new DateFormat("yyyy/MM/dd", "en_US").parse("2012/01/01")); // => 2012-01-01 00:00:00.000
Date elements that vary across locales include month name, week name, field order, etc. It also allows you to use any customized pattern to parse or format date-time strings under certain locales.
7. Compare two date
The DateTime class contains several handy methods, such as isAfter, isBefore, and isAtSameMomentAs, for comparing DateTime objects.
var date1 = DateTime.parse("1995-07-20 20:18:04");
var date2 = DateTime.parse("1996-07-20 20:18:04");
print(date1.isBefore(date2)); // => true
print(date1.isAfter(date2)); // => false
8. Get Different between two Dates
To find out how much time is between two DateTime objects use difference, which returns a Duration object:
var different=date2.difference(date1);
print(different.inDays); // => 366
9. Add days into the Date
Use the add and subtract methods with a Duration object to create a new DateTime object based on another.
var date1 = DateTime.parse("1995-07-20 20:18:04");
var newDate = date1.add(new Duration(days: 366));
print(newDate); // => 1996-07-20 20:18:04.000