Câu hỏi phỏng vấn Flutter
Câu hỏi

How to compare two dates that are...

Câu trả lời

Here's how you can compare two dates that are constructed differently in Dart:

Comparing Dates in Dart

In Dart, you can compare dates using the compareTo() method or the comparison operators (<, >, <=, >=, ==). Here's how to compare dates constructed differently:

1. Using DateTime objects

If both dates are represented as DateTime objects, you can directly compare them using the comparison operators or the compareTo() method:

dart Copy
DateTime date1 = DateTime(2023, 5, 21);
DateTime date2 = DateTime.now();

if (date1.compareTo(date2) < 0) {
  print('date1 is before date2');
} else if (date1.compareTo(date2) > 0) {
  print('date1 is after date2');
} else {
  print('date1 is the same as date2');
}

2. Comparing dates with different formats

If one date is represented as a String or a different format, you'll need to parse it into a DateTime object before comparing:

dart Copy
String dateString = '2023-05-21';
DateTime parsedDate = DateTime.parse(dateString);
DateTime currentDate = DateTime.now();

if (parsedDate.compareTo(currentDate) < 0) {
  print('parse...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

Do you know what Ephemeral state means?

senior

What does a class with a method named ._() mean in Dart/Flutter?

middle

What is ScopedModel / BLoC Pattern?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào