检查datetime变量是今天,明天还是昨天

时间:2019-01-27 18:27:54

标签: dart

作为主题,我不知道如何检查datetime变量是今天,明天还是昨天。

我没有在类成员中找到方法。

6 个答案:

答案 0 :(得分:18)

虽然以上答案是正确的,但我想提供一个更紧凑,更灵活的选择:

/// 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

答案 1 :(得分:11)

使用dart扩展名可以帮助使代码更优雅。您可以使用以下命令创建实用程序类:

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

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

然后,每当您需要知道今天是今天还是昨天时,请将实用程序类导入到需要的文件中,然后像在DateTime类中内置的那样调用相应的函数。

Text(
    myDate.isToday() ? "Today" 
  : myDate.isYesterday() ? "Yesterday" 
  : DateFormat("dd MMM").format(myDate)
)

答案 2 :(得分:4)

简单的isToday检查:

bool isToday(DateTime date) {
  final now = DateTime.now();
  final diff = now.difference(date).inDays;
  return diff == 0 && now.day == date.day;
}

答案 3 :(得分:1)

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 aDateTime = ...
final aDate = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);
if(aDate == today) {
  ...
} else (aDate == yesterday) {
  ...
} else (aDate == tomorrow) {
  ...
}

命中:now.day - 1now.day + 1在日期不同的年份或月份时效果很好。

答案 4 :(得分:0)

这也可以做

 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;
         }

     }

 }

答案 5 :(得分:0)

一行代码:)

Text(
  date.isAfter(DateTime.now().subtract(Duration(days: 1)))
      ? 'Today'
      : DateFormat('EE, d MMM, yyyy').format(date),
),

对于 DateFormat 使用 import 'package:intl/intl.dart';