ssdesign
ssdesign

Reputation: 2821

How to convert timestamp string to millisecond int

I am using the Stopwatch Timer plugin (https://pub.dev/packages/stop_watch_timer) This plugin gives me time elapsed as a 'string'. So my text looks like:

00:00:03.45 // hours:minutes:seconds.milliseconds

Now I need to use this time information to calculate the score in the game. Do you know how I can convert this string into millisecond int so that i can use it to do math calculations?

My logic would be to multiple the time taken with another value to determine the score. THe more time user takes, the higher (poor) the score would be.

Any help is appreciated. Thanks

Upvotes: 2

Views: 3656

Answers (3)

Robert Sandberg
Robert Sandberg

Reputation: 8607

I would use DateFormat like this:

final timeStr = '00:00:03.45';
final format = DateFormat('HH:mm:ss.S');
final dt = format.parse(timeStr, true);
print(dt.millisecondsSinceEpoch);

which would print:

3045

Note: Will require intl package to be imported:

import 'package:intl/intl.dart';

Upvotes: 6

fravolt
fravolt

Reputation: 3001

A quite manual but functional solution to this, using Duration, would be something like

  Duration getDuration(String elapsed) {
    List<String> splits = elapsed.split(':');
    List<String> minSplits = splits[2].split('.');

    int hours = int.parse(splits[0]);
    int minutes = int.parse(splits[1]);
    int seconds = int.parse(minSplits[0]);
    
    // pad with 0s to make sure 45 -> 450
    int millis = int.parse(minSplits[1].padRight(3, '0'));
    
    // create a duration object for ease of calculation/access
    Duration duration = Duration(
      hours: hours,
      minutes: minutes,
      seconds: seconds,
      milliseconds: millis,
    );
    
    return duration;
  }
  
  
  
  String elapsed = '00:00:03.45';
  Duration duration = getDuration(elapsed);
  print(duration.inMilliseconds);

Upvotes: 0

Chirag Bargoojar
Chirag Bargoojar

Reputation: 1214

You can use Duration() and get the milliseconds like this.

I use time as 10:12:23.24 and split through every item and get hr, min, sec, millisec.

void main() {
String test = "10:12:23.24";
String hr = test.split(":")[0];
// print(hr);
String minutes = test.split(":")[1];
// print(minutes);
String seconds = test.split(":")[2].split(".")[0];
// print(seconds);
String milliseconds = test.split(":")[2].split(".")[1];
// print(milliseconds);

Duration duration = Duration(
  hours: int.tryParse(hr) ?? 0,
  minutes: int.tryParse(minutes) ?? 0,
  seconds: int.tryParse(seconds) ?? 0,
  milliseconds: int.tryParse(milliseconds) ?? 0);
  print(duration.inMilliseconds);
}

Output will be in milliseconds: 36743024 <- Output

You can try here

Upvotes: 1

Related Questions