0

I have a date-time in epoch format: 1636466227 I want to convert it into timestamps like this: X months, X weeks ago. How can I do that with Dart

  • Does this help: https://stackoverflow.com/questions/50632217/converting-timestamp – Rohith Nambiar Mar 07 '22 at 07:12
  • Assuming that 1636466227 is a number of *seconds* since the Unix epoch, you can convert it to milliseconds and then use [`DateTime.fromMillisecondsSinceEpoch`](https://api.dart.dev/stable/dart-core/DateTime/DateTime.fromMillisecondsSinceEpoch.html) to create a `DateTime` object. From there, you can use something such as [`package:timeago`](https://pub.dev/packages/timeago) to get a friendlier description. (There seem to be a number of packages that do this; I just picked one that seems to be popular. I don't have any experience with that particular one.) – jamesdlin Mar 07 '22 at 07:12

1 Answers1

0

Create a utils functions

      static String getAge(int timeInMillSec) {
        static const SECOND = 1;
        static const MINUTE = 60 * SECOND;
        static const HOUR = 60 * MINUTE;
        static const DAY = 24 * HOUR;
        static const MONTH = 30 * DAY;
        static const YEAR = 12 * MONTH;
        const PERIODS = [YEAR, MONTH, DAY, HOUR, MINUTE, SECOND];
        const PERIOD_SUFFIXES = ["years", "months", "days", "hrs", "mins", "secs"];
        final time = DateTime.fromMillisecondsSinceEpoch(timeInMillSec);
        final diff = DateTime.now().difference(time).inSeconds;
        for (var i = 0; i < PERIODS.length; i++) {
          final v = diff ~/ PERIODS[i];
          if (v > 0) {
            return "$v${PERIOD_SUFFIXES[i]}";
          }
        }
        return "0s";
      }

Pass the milliseconds to this functions to get X mins, X hrs, X days etc.

Ganesh Bhat
  • 246
  • 4
  • 19