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

senior

What are Global Keys?

middle

Where are the layout files? Why doesn’t Flutter have layout files?

senior

When would you use App state or Ephemeral state over another?

Bình luận

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

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