Flutter:查找两个日期之间的天数

问题描述:

我目前有一个用户的个人资料页面,可以显示他们的出生日期和其他详细信息.但我打算通过计算今天的日期和从用户那里获得的出生日期之间的差异来找到他们生日前的几天.

I currently have a user's profile page that brings out their date of birth and other details. But I am planning to find the days before their birthday by calculating the difference between today's date and the date of birth obtained from the user.

用户的出生日期

这是使用 intl 包 获得的今天的日期.

And this is today's date obtained by using the intl package.

今天的日期

I/flutter ( 5557): 09-10-2018

我现在面临的问题是,如何计算这两个日期的天数差?

The problem I am facing now is, How do I calculate the difference in days of these two dates?

是否有任何特定的公式或软件包可供我查看?

Are there any specific formulas or packages that are available for me to check out?

您可以使用DateTime类提供的difference方法

You can use the difference method provide by DateTime class

 //the birthday's date
 final birthday = DateTime(1967, 10, 12);
 final date2 = DateTime.now();
 final difference = date2.difference(birthday).inDays;

更新

由于你们中的许多人报告此解决方案存在错误并避免更多错误,我将在此处添加@MarcG 提出的正确解决方案,所有功劳都归功于他.

Since many of you reported there is a bug with this solution and to avoid more mistakes, I'll add here the correct solution made by @MarcG, all the credits to him.

  int daysBetween(DateTime from, DateTime to) {
     from = DateTime(from.year, from.month, from.day);
     to = DateTime(to.year, to.month, to.day);
   return (to.difference(from).inHours / 24).round();
  }

   //the birthday's date
   final birthday = DateTime(1967, 10, 12);
   final date2 = DateTime.now();
   final difference = daysBetween(birthday, date2);

这是完整解释的原始答案:https://*.com/a/67679455/666221

This is the original answer with full explanation: https://*.com/a/67679455/666221