Home > Software engineering >  API Response Date Format
API Response Date Format

Time:10-11

I'm using Google Apps Script making an API request to get a date. The date, however, is coming back as a number in scientific notation (1.635218706E9) which I'm assuming is in the format of milliseconds from 1970. After converting it from scientific notation to a regular number (1635218706) creating a new javascript date with it the wrong date and year. It should be Oct 25 2021, but instead gives Dec 31 1969.

Am I missing something when creating a new date from the number? And is there a way just have the API respond with a more readable date instead of milliseconds from 1970?

CodePudding user response:

Just in case. I found if you multiply this number by 1000 and feed it to Data object you can get something a little bit more reasonable:

var seconds = 1.635218706E9;
var date = new Date(seconds*1000);
console.log(date); // output: 2021-10-26T03:25:06.000Z

var date_str = [date.getFullYear(), date.getMonth() 1, date.getDate()].join('/')
console.log(date_str); // output: 2021/10/26

It looks like the API gives you seconds.

CodePudding user response:

you can use toLocaleString / toLocaleDateString

so the code is like this

const dates = new Date()
const fullDates = dates.toLocaleString('en-US')

you can read in documentation here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

  • Related