Home > Software design >  millisecondSinceEpoch returning weird value when parsing date around 1969
millisecondSinceEpoch returning weird value when parsing date around 1969

Time:04-21

I don't know if this is a bug or if I'm using this method incorrectly. Can someone explain to me why I got a weird value when parsing this date?

This is the minimal script:

void main(){
  DateTime zero = DateTime.fromMillisecondsSinceEpoch(0);
  print(zero.millisecondsSinceEpoch);
  DateTime errorDate2 = DateTime(1969,1,1);
  print(errorDate2.millisecondsSinceEpoch);
  DateTime errorDate = DateTime(1969,10,2);
  print(errorDate.millisecondsSinceEpoch);
}

Based on my sample, the result seems fine when I parse dates bigger than 0 milliseconds since the epoch. But it gets weird when I parse some date less than 0 milliseconds since the epoch.

From that script, I got this output

0
-31536000000
-7862400000

I parse that output to this website. In the first and second results, the results are fine, but in the third result, I got a date around 1720.

Can someone explain to me what happens to that function? Did I use it wrong? What should I do when I want to parse a date less than 0 milliseconds since the epoch?

CodePudding user response:

In a computing context, an epoch is the date and time relative to which a computer's clock and timestamp values are determined. The epoch traditionally corresponds to 0 hours, 0 minutes, and 0 seconds (00:00:00) Coordinated Universal Time (UTC) on a specific date, which varies from system to system. Most versions of Unix, for example, use January 1, 1970 as the epoch date; Windows uses January 1, 1601; Macintosh systems use January 1, 1904, and Digital Equipment Corporation's Virtual Memory System (VMS) uses November 17, 1858.

So here epoch time starts on January 1, 1970, so it will give you a minus value for milliseconds.

You can still parse the date. it will gave just minus value nothing else.

void main() {
    DateTime zero = DateTime.fromMillisecondsSinceEpoch(0);
    print(zero.millisecondsSinceEpoch);
    DateTime errorDate2 = DateTime(1969,1,1);
    print(errorDate2.millisecondsSinceEpoch);
    DateTime errorDate = DateTime(1969,10,2);
    print(errorDate.millisecondsSinceEpoch);
    DateTime error3 = DateTime.fromMillisecondsSinceEpoch(errorDate.millisecondsSinceEpoch);
    print(error3);
  }

Result is

0
-31555800000
-7882200000
1969-10-02 00:00:00.000

CodePudding user response:

It seems that the bug comes from the website that I refer to it.

Thanks! @jamesdlin

  • Related