Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates that are constructed differently in Dart?

Tags:

flutter

dart

I am trying to compare two dates, one built with DateTime.parse() and another one build with DateTime(), but so fat I have not been sucessful.

Here is my code snippet.

void main(){
  String dateTime = '2020-02-03T08:30:00.000Z';
  int year = 2020;
  int month = 2;
  int day = 3;
  int hour = 8;
  int minute = 30;
  print(DateTime.parse(dateTime).isAtSameMomentAs(DateTime(year, month, day, hour, minute)));
}

The comparison method returns false, although the dates are supposed to be the same.

What is the correct way of going about this?

like image 958
user2583728 Avatar asked Oct 17 '25 20:10

user2583728


1 Answers

You may do that by converting the other date into utc and then comparing them with isAtSameMomentAs method. working code below:

void main(){
  String dateTime = '2020-02-03T08:30:00.000Z';
  int year = 2020;
  int month = 2;
  int day = 3;
  int hour = 8;
  int minute = 30;

  var dt = DateTime.utc(year,month,day,hour,minute);
  print(dt);

  print(DateTime.parse(dateTime).isAtSameMomentAs(dt));

  // 2020-02-03 08:30:00.000Z
  // 2020-02-03 08:30:00.000Z
  // true

}

Hope this answers your question.

like image 162
Darshan Avatar answered Oct 20 '25 11:10

Darshan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!