Flutter-如何找出年,月和日中两个日期之间的差异? [英] Flutter - How to find difference between two dates in years, months and days?
问题描述
我正在寻找一种使用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屋!