0

Background:

I'm working on a fit-bit fitness application. So I get updates from the fit-bit API with date, time and the heart-rate at that point in the following format:

date = "2021-02-01"
time = "14:15:00" 
bpm: 78

Now, I need to convert this to a timestamp and save the heart-rate in the format =>(timestamp: heart-rate) I query the heartrate data from the app based on the timetsamp - so they have to match.

Problem: I am parsing the given data using moment.js to get the timestamp,

let date = "2021-02-01"
let time = "14:15:00"
let t = moment(`${date} ${time}`, 'yyyy-mm-dd hh:mm:ss').valueOf();
console.log("Timestamp", t, new Date(t).toUTCString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

For the above code, I am getting different values:

On my backend server where the database is updated :

"Timestamp",  1609510500000 Fri, 01 Jan 2021 14:15:00 GMT Fri,

As you can see it maps to Jan 1, please help

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Blake
  • 47
  • 3
  • Are the date and time you receive in UTC? If so, you should be using `moment.utc(value, format)`. To get a `Date`, use `toDate()`, not `valueOf()` and `new Date()`. I'd also log it using `toISOString()`. – Heretic Monkey Feb 01 '21 at 21:31
  • 1
    Also, your format string is incorrect. Month is `MM`, not `mm`, which is minutes... – Heretic Monkey Feb 01 '21 at 21:33

1 Answers1

1

The reason you get different results on different systems is because a timestamp in the format YYYY-MM-DD hh:mm (i.e. without a timezone offset) will be treated as local, so the host system's offset will be used when parsing it and hence generating a UTC time value from it. That means it represents a different moment in time in systems where the timezone offset is different.

If you want to send a UTC time value to the server, create a valid ECMAScript timestamp (a version of ISO 8601), parse it to a Date then get its time value, e.g.

let date = "2021-02-01";
let time = "14:15:00";
let d = new Date(`${date}T${time}`); // Parse as local
let timeValue = d.getTime();
console.log(
  'Local: ' + d.toString() +
  '\nUTC  : ' + d.toISOString() +
  '\nTime value: ' + timeValue
);

It would also be useful to see Why does Date.parse give incorrect results?

If you have UTC values to begin with, you can just call Date.UTC with appropriate year, month, day, etc. values to get the time value to use as a timestamp directly (remembering that months are zero indexed, so subtract 1 from the calendar month number, e.g. Jan = 0, Feb = 1, etc.).

RobG
  • 142,382
  • 31
  • 172
  • 209