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

前端 未结 6 1265
梦毁少年i
梦毁少年i 2021-01-16 12:48

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\".

For J

6条回答
  •  青春惊慌失措
    2021-01-16 12:54

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

提交回复
热议问题