Flutter-如何找出年,月和日中两个日期之间的差异? [英] Flutter - How to find difference between two dates in years, months and days?

查看:361
本文介绍了Flutter-如何找出年,月和日中两个日期之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用DateTime解析两个日期以显示差异的方法. 我想采用以下格式:"X年,Y个月,Z天".

I'm looking for a way to use DateTime to parse two dates, to show the difference. I want to have it on the format: "X years, Y months, Z days".

对于JS,我们有momentjs库和以下代码 ::

For JS, we have momentjs library and following code::

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

是否有类似的库可用于实现 dart ?

Is there similar library available for dart that can help achieve this usecase?

推荐答案

我认为使用DateTime不可能完全轻松地完成您想要的操作.因此,您可以使用具有日期功能的 https://pub.dev/packages/time_machine 软件包时间处理:

I think it is not possible to do exactly what you want easily with DateTime. Therefore you can use https://pub.dev/packages/time_machine package that is quite powerful with date time handling:

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

这篇关于Flutter-如何找出年,月和日中两个日期之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆