Home > Back-end >  Different Timestamp Header Value When Request Service After 8 PM
Different Timestamp Header Value When Request Service After 8 PM

Time:12-17

I have some strange problem here, I need to send the current time in milisecond from android to authorize all user when try to request an API. My problem is, when I try to compare the header request and time server, it have some different, about 12 hours, and it happens after 8 PM everyday. When I try to call the API next morning, the header send correct timestamp with the server time.

Result After 8 PM

Time Request Header :  1639618812
Server Time         :  1639662014
Max 5 Minutes       :  1639662314
Min 5  Minutes      :  1639661714

This the result I tried just recently

Time Request Header :  1639704110
Server Time         :  1639704111
Max 5 Minutes       :  1639704411
Min 5 Minutes       :  1639703811

This is how I generated timestamp with flutter

  static String createXTimestamp() {
    DateTime test = DateTime.parse("1970-01-01 00:00:00");
    String now = DateFormat('yyyy-MM-dd hh:mm:ss').format(DateTime.now().toUtc());
    var tStamp = DateTime.parse(now).millisecondsSinceEpoch - test.millisecondsSinceEpoch;
    return tStamp.toString().substring(0,10);
  }

This is how it processed in NodeJs

  const dateNow =  Math.floor(new Date().getTime() / 1000);
    var max5 = dateNow   300;
    var min5 = dateNow - 300;
    var time = req.headers.time;
    if(time >= min5 && time <= max5)
        //always return false
    else
        res.json({error_code: 401, message: "Unauthorized User"});

This really confuse me, so I really need some help here. Thank you.

CodePudding user response:

This sounds like a timezone bug. I don't think the createXTimestamp is doing the correct thing. There's a few timezone bugs in there, where the precision of the timezone is getting lost, and replaced with local timezone.

Also, you say "milliseconds since epoch" -- the .substring(0,10) is stripping off the milliseconds, and on the node side you divide by 1000 to get seconds as well.

If the goal is to return seconds since epoch, I don't think you need the test variable at all, and you can replace all of that function with the following:

static String createXTimestamp() {
  return DateTime.now().toUtc().millisecondsSinceEpoch.toString().substring(0, 10);
}
  • Related