skip to Main Content

Always when i want to use microsecond of DateTime it is always return 0.

So i made this test and set microsecond to 345:

void main () {
  DateTime duration = DateTime(2024, 1, 1, 0, 0, 0, 0, 345);

  print(duration.microsecond);
  print(duration.millisecond);

  print(duration);
}

and this is what i got:

0
0
2024-01-01 00:00:00.000

and if i set microsecond to >=500 (exp : 675), this is the result:

0
1
2024-01-01 00:00:00.001

Is this bug or i am missing somethings ?

2

Answers


  1. It works fine if you don’t run it on Web.

    The "issue" is that Flutter Web rounds microseconds in DateTime objects because its internal time thingy can’t handle values between microseconds. It just chops it off to the nearest whole microsecond.

    For super precise microsecond fun, use the Duration class instead. It lets you create durations with specific microsecond values, no rounding required!

    Code

    Duration duration = Duration(microseconds: 345);
    print(duration.inMicroseconds); // Prints 345
    
    Login or Signup to reply.
  2. If you run your code using dart command, it prints the actual microseconds (345 in your case), but in flutter, there are some platform-specific limitations. For instance, when using Flutter for web development, Web browsers limit timing resolution to milliseconds in an attempt to mitigate against timing-based attacks. (Mentioned here: How do I get DateTime in flutter with microseconds?) so microseconds will not be reported, but again, using android (which I’ve tested now), the actual value is returned.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search