Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to Compare Two DateTime in Dart/Flutter

In this example, we are going to show you the detailed way to compare DateTime in Dart and Flutter. DateTime is an important component, you may need to compare two DateTime in Dart/Flutter.

DateTime.compareTo(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.compareTo(dt2) == 0){
    print("Both date time are at same moment.");
}

if(dt1.compareTo(dt2) < 0){
    print("DT1 is before DT2");
}

if(dt1.compareTo(dt2) > 0){
    print("DT1 is after DT2");
}

DateTime.isAtSameMomentAs(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.isAtSameMomentAs(dt2)){
   print("Both DateTime are at same moment.");
}

DateTime.isBefore(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.isBefore(dt2)){
   print("DT1 is before DT2");
}

DateTime.isAfter(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.isAfter(dt2)){
   print("DT1 is after DT2");
}

Flutter/Dart Full Example:

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {

    DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
    DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

    return Scaffold(
         appBar: AppBar(
            title: Text("Compare Date Time in FLutter"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:[
         
                      Text("DT 1:" + dt1.toString()),
                      Text("DT 2" + dt2.toString()),

                      Text(dt1.isAfter(dt2)?"DT1 is after DT2":"DT1 is not after DT2"),
                      Text(dt1.isBefore(dt2)?"DT1 is before DT2":"DT1 is not before DT2"),

                ]
             ),
          )
      );
  }
}

Output Screenshot:

In this way, you can compare two Date and Time in Flutter using Dart.

No any Comments on this Article


Please Wait...