Convert timestamp difference to years, months and weeks

Viewed 126

I would like to add to the code below as many options as possible to display how much time has passed. Right not I have Hours:Minuts:Seconds ... I was thinking of Years:Months:Weeks:Hours:Minutes:Seconds. Is something like this possible?

final currentTimestamp = Timestamp.now();
final timestamp = currentTimestamp.seconds;
final firestoreTimestamp = widget.timestamp;

final diff = timestamp - firestoreTimestamp.seconds;

timerSubscription = timerStream.listen((int newTick) {
  if (!mounted) return;
  setState(() {
    hoursStr = (((newTick + diff) / (60 * 60)) % 60)
        .floor()
        .toString()
        .padLeft(2, '0');
    minutesStr =
        (((newTick + diff) / 60) % 60).floor().toString().padLeft(2, '0');
    secondsStr = ((newTick + diff) % 60).floor().toString().padLeft(2, '0');
  });
})
2 Answers

I recommend time_machine package to achieve this:

import 'package:time_machine/time_machine.dart';

void main() {
  final start = LocalDateTime(2012, 1, 1, 14, 0, 0);
  final end = LocalDateTime(2013, 3, 9, 16, 3, 4);

  final period = Period.differenceBetweenDateTime(start, end, PeriodUnits.allUnits);

  print("years: ${period.years}");
  print("months: ${period.months}");
  print("weeks: ${period.weeks}");
  print("days: ${period.days}");
  print("hours: ${period.hours}");
  print("minutes: ${period.minutes}");
  print("seconds: ${period.seconds}");
}

Try this:

print(new DateFormat.yMMMd().format(new DateTime.now()));

You can change yMMMd to what you want using list of formats below:

https://api.flutter.dev/flutter/intl/DateFormat-class.html

Then parse it using Parse or ParseExact. Parse will try to figure out format but if you want to specify format use ParseExact.

Related