Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the time elapsed from a timestamp?

Tags:

flutter

dart

To be more precise, I would like to display the number of minutes passed since a timestamp fetched from an API. Should Stopwatch or Timer be used, or something else?

like image 327
Toni Avatar asked Nov 01 '25 18:11

Toni


2 Answers

In your case, you should first parse your timestamp to a DateTime object. Then you can retrieve the time delta between the fetched DateTime and the current time by using the different method of the DateTime class.

final Duration myDuration = DateTime.parse(myTimeStamp).difference(DateTime.now));

For more information, please visit https://api.dart.dev/stable/2.10.4/dart-core/DateTime/difference.html.

Timer and Stopwatch are used for async work; you do not need such complexity level in your case.

like image 102
Gaspard Merten Avatar answered Nov 04 '25 08:11

Gaspard Merten


I'd suggest something like the below. You can update the duration associated with the Timer to define how often it rebuilds the widget.

I've also left it up to you to decide how you would like to format the duration.

class ElapsedTime extends StatefulWidget {
  final String timestamp;

  const ElapsedTime({
    Key key,
    @required this.timestamp,
  }) : super(key: key);

  @override
  _ElapsedTimeState createState() => _ElapsedTimeState();
}

class _ElapsedTimeState extends State<ElapsedTime> {
  Timer _timer;

  DateTime _initialTime;
  String _currentDuration;


  @override
  void didUpdateWidget(ElapsedTime oldWidget) {
    super.didUpdateWidget(oldWidget);

    if(widget.timestamp != oldWidget.timestamp) {
      _initialTime = _parseTimestamp();
      _currentDuration = _formatDuration(_calcElapsedTime());
    }
  }

  @override
  void initState() {
    super.initState();

    _initialTime = _parseTimestamp();
    _currentDuration = _formatDuration(_calcElapsedTime());

    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      setState(() {
        _currentDuration = _formatDuration(_calcElapsedTime());
      });
    });
  }

  Duration _calcElapsedTime() => _initialTime.difference(DateTime.now());

  DateTime _parseTimestamp() => DateTime.parse(widget.timestamp);

  // TODO update this to fit your own needs
  String _formatDuration(final Duration duration) => duration.toString();

  @override
  void dispose() {
    _timer?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text(_currentDuration);
  }
}

like image 33
JayDev Avatar answered Nov 04 '25 09:11

JayDev