检查日期时间变量是否为今天、明天或昨天。

71

我不知道如何检查datetime变量是否是今天、明天或昨天。

在类成员中,我没有找到相应的方法。

8个回答

114
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final yesterday = DateTime(now.year, now.month, now.day - 1);
final tomorrow = DateTime(now.year, now.month, now.day + 1);


final dateToCheck = ...
final aDate = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);
if(aDate == today) {
  ...
} else if(aDate == yesterday) {
  ...
} else(aDate == tomorrow) {
  ...
}

提示: now.day - 1now.day + 1 可以在涉及不同年份或月份的日期上正常使用。


52

尽管上面的回答是正确的,但我想提供一个更简洁、更灵活的替代方案:

/// Returns the difference (in full days) between the provided date and today.
int calculateDifference(DateTime date) {
  DateTime now = DateTime.now();
  return DateTime(date.year, date.month, date.day).difference(DateTime(now.year, now.month, now.day)).inDays;
}

所以,如果您想检查date是否为:

  • 昨天calculateDifference(date) == -1
  • 今天calculateDifference(date) == 0
  • 明天calculateDifference(date) == 1

14
这里有一个缺陷。如果“你要检查的日期”和“今天的日期”的差异少于24小时,它将告诉你差异为0天,这是正确的,但会造成误导。这些日期是不同的,但它们之间的小时数没有超过一天。 - Charden Daxicen
7
通过仅使用年份、月份和日期创建新的DateTime,我们不考虑小时数。 - Skyost
这种方法还有一个例外。如果两个日期来自不同的时区,差异函数将不会考虑到这一点。当处理服务器持久化的UTC日期和设备上的本地时区日期时,比较是不正确的。 - Vlad Nicula

41
使用Dart扩展可以使您的代码更加优雅。您可以创建一个带有以下内容的实用类:
extension DateHelpers on DateTime {
  bool get isToday {
    final now = DateTime.now();
    return now.day == day && now.month == month && now.year == year;
  }

  bool get isYesterday {
    final yesterday = DateTime.now().subtract(const Duration(days: 1));
    return yesterday.day == day &&
        yesterday.month == month &&
        yesterday.year == year;
  }
}


然后,每当你需要知道一个日期是今天还是昨天时,将这个实用类导入到你需要它的文件中,然后像内置在DateTime类中一样调用相应的函数。
Text(
    myDate.isToday() ? "Today" 
  : myDate.isYesterday() ? "Yesterday" 
  : DateFormat("dd MMM").format(myDate)
)

这可以是一个getter而不是一个函数,因为我们不传递参数,但总体上这是最好的答案。 - Adam Smaka

17

@34mo的答案已更新为Flutter Lint 2021

extension DateUtils on DateTime {
  bool get isToday {
    final now = DateTime.now();
    return now.day == day && now.month == month && now.year == year;
  }

  bool get isTomorrow {
    final tomorrow = DateTime.now().add(const Duration(days: 1));
    return tomorrow.day == day &&
        tomorrow.month == month &&
        tomorrow.year == year;
  }

  bool get isYesterday {
    final yesterday = DateTime.now().subtract(const Duration(days: 1));
    return yesterday.day == day &&
        yesterday.month == month &&
        yesterday.year == year;
  }
}

11
一个简单的isToday检查:
/// Returns `true` if the [date] is today. Respects the time zone.
/// https://dev59.com/hVQJ5IYBdhLWcg3wMCx_#60213219
bool isToday(DateTime date) {
  final DateTime localDate = date.toLocal();
  final now = DateTime.now();
  final diff = now.difference(localDate).inDays;
  return diff == 0 && now.day == localDate.day;
}

这是最好的!我在处理其他答案时遇到了有关时区的问题。+1 - Godwin Mathias

0

为了更简化操作,您可以按照以下步骤进行。

String myDate = "01/09/2022";

例如,我需要检查这个“myDate”是今天还是明天。

因此,我只需调用此函数即可:

String dateConverter(String myDate) {
  String date;
  DateTime convertedDate =
      DateFormat("DD/MM/YYYY").parse(myDate.toString());
  final now = DateTime.now();
  final today = DateTime(now.year, now.month, now.day);
  final yesterday = DateTime(now.year, now.month, now.day - 1);
  final tomorrow = DateTime(now.year, now.month, now.day + 1);

  final dateToCheck = convertedDate;
  final checkDate = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);
  if (checkDate == today) {
    date = "Today";
  } else if (checkDate == yesterday) {
    date = "Yesterday";
  } else if (checkDate == tomorrow) {
    date = "Tomorrow";
  } else {
    date = myDate;
  }
  return date;
} 

如果myDate不是今天、明天或昨天,那么它将返回我的默认日期字符串。

0

检查是否为今天的简单方法

   bool isToday(DateTime date) {
        final now = DateTime.now();

        return now.year == date.year &&
            now.month == date.month &&
            now.day == date.day;
      }

-1

这个也可以完成工作

 String checkDate(String dateString){

   //  example, dateString = "2020-01-26";

   DateTime checkedTime= DateTime.parse(dateString);
   DateTime currentTime= DateTime.now();

   if((currentTime.year == checkedTime.year)
          && (currentTime.month == checkedTime.month)
              && (currentTime.day == checkedTime.day))
     {
        return "TODAY";

     }
   else if((currentTime.year == checkedTime.year)
              && (currentTime.month == checkedTime.month))
     {
         if((currentTime.day - checkedTime.day) == 1){
           return "YESTERDAY";
         }else if((currentTime.day - checkedTime.day) == -1){
            return "TOMORROW";
         }else{
            return dateString;
         }

     }

 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接