简体   繁体   English

Flutter - 如何找到两个日期之间的年、月和日差异?

[英]Flutter - How to find difference between two dates in years, months and days?

I'm looking for a way to use DateTime to parse two dates, to show the difference.我正在寻找一种使用DateTime来解析两个日期以显示差异的方法。 I want to have it on the format: "X years, Y months, Z days".我想把它放在格式上:“X 年,Y 个月,Z 天”。

For JS, we have momentjs library and following code ::对于 JS,我们有momentjs库和以下代码::

var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var years = a.diff(b, 'year');
b.add(years, 'years');

var months = a.diff(b, 'months');
b.add(months, 'months');

var days = a.diff(b, 'days');

console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days

Is there similar library available for dart that can help achieve this usecase? dart是否有类似的库可以帮助实现这个用例?

I think it is not possible to do exactly what you want easily with DateTime.我认为使用 DateTime 不可能轻松地完成您想要的操作。 Therefore you can use https://pub.dev/packages/time_machine package that is quite powerful with date time handling:因此,您可以使用在日期时间处理方面非常强大的https://pub.dev/packages/time_machine package:

import 'package:time_machine/time_machine.dart';

void main() {
  LocalDate a = LocalDate.today();
  LocalDate b = LocalDate.dateTime(DateTime(2022, 1, 2));
  Period diff = b.periodSince(a);
  print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}");
}

for hours/minutes/seconds precision:小时/分钟/秒精度:

import 'package:time_machine/time_machine.dart';

void main() {
  LocalDateTime a = LocalDateTime.now();
  LocalDateTime b = LocalDateTime.dateTime(DateTime(2022, 1, 2, 10, 15, 47));
  Period diff = b.periodSince(a);
  print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}; hours: ${diff.hours}; minutes: ${diff.minutes}; seconds: ${diff.seconds}");
}

What you are looking for is the DartDateTime class You can get close to what you want in moment.js with您正在寻找的是 DartDateTime class您可以在 moment.js 中接近您想要的

main() {
  var a = DateTime.utc(2015, 11, 29);
  var b = DateTime.utc(2007, 06, 27);

  var years = a.difference(b);
  print(years.inDays ~/365);

}

There is no inYears or inMonths option for DateTime though that's why the year is divided in the print. DateTime 没有 inYears 或 inMonths 选项,但这就是打印中划分年份的原因。 the difference function returns the difference in seconds so you have to process it yourself to days.差异 function 以秒为单位返回差异,因此您必须自己处理几天。

You could write an extension on duration class to format it:您可以在持续时间 class 上编写扩展名来格式化它:

extension DurationExtensions on Duration {
  String toYearsMonthsDaysString() {
    final years = this.inDays ~/ 365
    // You will need a custom logic for the months part, since not every month has 30 days
    final months = (this.inDays ~% 365) ~/ 30
    final days = (this.inDays ~% 365) ~% 30

    return "$years years $months months $days days";
  }
}

The usage will be:用法将是:

final date1 = DateTime()
final date2 = DateTime()
date1.difference(date2).toYearsMonthsDaysString()

You can use Jiffy Package for this like this您可以像这样使用Jiffy Package

var jiffy1 = Jiffy("2008-10", "yyyy-MM");
var jiffy2 = Jiffy("2007-1", "yyyy-MM");

jiff1.diff(jiffy2, Units.YEAR); // 1
jiff1.diff(jiffy2, Units.YEAR, true);

try intl package with the following code:使用以下代码尝试 intl package:

import 'package:intl/intl.dart';

String startDate = '01/01/2021';
String endDate = '01/01/2022';

final start = DateFormat('dd/MM/yyyy').parse(startDate);
final end = DateFormat('dd/MM/yyyy').parse(endDate);

Then, you can calculate the duration between the two dates with the following code:然后,您可以使用以下代码计算两个日期之间的持续时间:

final duration = end.difference(start);

To obtain the number of years, months and days, you can do the following:要获取年、月、日的数量,您可以执行以下操作:

final years = duration.inDays / 365;
final months = duration.inDays % 365 / 30;
final days = duration.inDays % 365 % 30;

Finally, you can use these variables to display the result in the desired format:最后,您可以使用这些变量以所需格式显示结果:

    final result = '${years.toInt()} years ${months.toInt()} months y ${days.toInt()} days';
final firstDate = DateTime.now();
final secondDate = DateTime(firstDate.year, firstDate.month - 20);

final yearsDifference = firstDate.year - secondDate.year;
final monthsDifference = (firstDate.year - secondDate.year) * 12 +
    firstDate.month - secondDate.month;
final totalDays = firstDate.difference(secondDate).inDays;

Simple approach, no packages needed.简单的方法,不需要包。

I create my own class for Gregorian Dates, and i create a method which handle this issue, it calculates "logically" the difference between to dates in years, months, and days... i actually create the class from scratch without using any other packages (including DateTime package) but here i use DateTime package to illustrate how this method works.. until know it works fine for me...我为公历创建了自己的 class,并创建了一种处理此问题的方法,它“逻辑地”计算日期之间的年、月和日之间的差异......我实际上是从头开始创建 class 而不使用任何其他包(包括 DateTime 包),但在这里我使用 DateTime package 来说明这种方法是如何工作的......直到知道它对我来说很好......

method to determine if it's a leap year or no:判断是否闰年的方法:

    static bool leapYear(DateTime date) {
    if(date.year%4 == 0) {
      if(date.year%100 == 0){
        return date.year%400 == 0;
      }
      return true;
    }
    return false;
  }

this is the method which calculate the difference between two dates in years, months, and days.这是计算年、月和日两个日期之间差异的方法。 it puts the result in a list of integers:它将结果放入整数列表中:

     static List<int> differenceInYearsMonthsDays(DateTime dt1, DateTime dt2) {
    List<int> simpleYear = [31,28,31,30,31,30,31,31,30,31,30,31];
    if(dt1.isAfter(dt2)) {
      DateTime temp = dt1;
      dt1 = dt2;
      dt2 = temp;
    }
    int totalMonthsDifference = ((dt2.year*12) + (dt2.month - 1)) - ((dt1.year*12) + (dt1.month - 1));
    int years = (totalMonthsDifference/12).floor();
    int months = totalMonthsDifference%12;
    late int days;
    if(dt2.day >= dt1.day) {days = dt2.day - dt1.day;}
    else {
      int monthDays = dt2.month == 3
          ? (leapYear(dt2)? 29: 28)
          : (dt2.month - 2 == -1? simpleYear[11]: simpleYear[dt2.month - 2]);
      int day = dt1.day;
      if(day > monthDays) day = monthDays;
      days = monthDays - (day - dt2.day);
      months--;
    }
    if(months < 0) {
      months = 11;
      years--;
    }
    return [years, months, days];
  }

the method which calculate the difference between two dates in months, and days:计算两个日期在月和天之间的差异的方法:

static List<int> differenceInMonths(DateTime dt1, DateTime dt2){
    List<int> inYears = differenceInYearsMonthsDays(dt1, dt2);
    int difMonths = (inYears[0]*12) + inYears[1];
    return [difMonths, inYears[2]];
  }

the method which calculate the difference between two dates in days:以天为单位计算两个日期之间差异的方法:

static int differenceInDays(DateTime dt1, DateTime dt2) {
    if(dt1.isAfter(dt2)) {
      DateTime temp = dt1;
      dt1 = dt2;
      dt2 = temp;
    }
    return dt2.difference(dt1).inDays;
  }

usage example:用法示例:

void main() {
  DateTime date1 = DateTime(2005, 10, 3);
  DateTime date2 = DateTime(2022, 1, 12);
  List<int> diffYMD = GregorianDate.differenceInYearsMonthsDays(date1, date2);
  List<int> diffMD = GregorianDate.differenceInMonths(date1, date2);
  int diffD = GregorianDate.differenceInDays(date1, date2);

  print("The difference in years, months and days: ${diffYMD[0]} years, ${diffYMD[1]} months, and ${diffYMD[2]} days.");
  print("The difference in months and days: ${diffMD[0]} months, and ${diffMD[1]} days.");
  print("The difference in days: $diffD days.");
}

output: output:

The difference in years, months and days: 16 years, 3 months, and 9 days.
The difference in months and days: 195 months, and 9 days.
The difference in days: 5945 days.

DateTime difference in years is a specific function, like this: DateTime 年差是特定的 function,如下所示:

  static int getDateDiffInYear(DateTime dateFrom, DateTime dateTo) {
    int sign = 1;
    if (dateFrom.isAfter(dateTo)) {
      DateTime temp = dateFrom;
      dateFrom = dateTo;
      dateTo = temp;
      sign = -1;
    }
    int years = dateTo.year - dateFrom.year;
    int months = dateTo.month - dateFrom.month;
    if (months < 0) {
      years--;
    } else {
      int days = dateTo.day - dateFrom.day;
      if (days < 0) {
        years--;
      }
    }
    return years * sign;
  }
DateTime a = DateTime(2015, 11, 29);
DateTime b = DateTime(2007, 06, 27);
int days = a.difference(b).inDays;

the answer is yes, you can easilly achieve it with DateTime class in Dart.答案是肯定的,您可以使用 Dart 中的 DateTime class 轻松实现。 See:https://api.dart.dev/stable/2.8.3/dart-core/DateTime-class.html参见:https://api.dart.dev/stable/2.8.3/dart-core/DateTime-class.html

Example例子

void main() {
  var moonLanding = DateTime(1969,07,20)
  var marsLanding = DateTime(2024,06,10);
  var diff = moonLanding.difference(marsLanding);

  print(diff.inDays.abs());
  print(diff.inMinutes.abs());
  print(diff.inHours.abs());
}

outputs: 20049 28870560 481176输出:20049 28870560 481176

difHour = someDateTime.difference(DateTime.now()).inHours;
    difMin = (someDateTime.difference(DateTime.now()).inMinutes)-(difHour*60);

and same for years and days年日相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在颤动中查找两个日期之间的月数和天数 - Find number of months and days between two dates in flutter 计算两个日期之间开始的天数/周数/月数/年数 - Calculate number of days/weeks/months/years begins between two dates 年日时分格式中两个日期之间的差异 - Difference between two dates in years days hours minutes format 在 VB 中使用 DateDiff() 以月和日为单位查找 2 个日期之间的差异 - Using DateDiff() in VB to find the difference between 2 dates in months and days 计算 Android 中两个日期之间的年月 - Calculate Years and Months between Two Dates in Android 如何在 python 中找到两个日期之间的月份? 不基于仅基于月值的 30 天? - how to find the months between two dates in python? Not based on 30 days based on month value only? 如何在 Flutter 中获取两个日期之间的天数 - How to get days between two dates in Flutter 如何使用Python查找两个日期之间的年份差异? (如果一个人超过18岁,请进行锻炼) - How can I find the difference in years between two dates using Python? (Work out if a person is over 18) 以月和日为单位计算两个日期之间的时间段 - Calculate period between two dates in months and days 在.net中找到两个时间戳之间的完整日历年,月,日和小时最容易浪费时间 - Easiest wasy to find full calendar years, months, days and hours between two time stamps in .net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM