-2

I'm using an API in javascript that retrieves several information of stocks such as open, high, low and closing prices as well as date. However,this date is in epoch format (date: 1627047000, for example). How could I format this in this code so that I could have something like DD/MM/YYYY?

const yahooStockAPI  = require('yahoo-stock-api');

async function main()  {
    const startDate = new Date('07/01/2021');
    const endDate = new Date('07/25/2021');
    console.log(await yahooStockAPI.getHistoricalPrices(startDate, endDate, 'AMZN', '1d'));
}
main();

Thank you in advance!

Rafael
  • 37
  • 6
  • Parsing timestamps with the built–in parser as in `new Date('07/01/2021')` is strongly discouraged, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). Much better to give the parts directly to the constructor: `new Date(2021, 6, 1)` for 2021-07-01. – RobG Aug 08 '21 at 00:18

1 Answers1

1

Just multiply the epoch value times 1000 to convert to milliseconds (which is what javascript dates are based on) and pass to a new Date object then you can use Intl.DateTimeFormat to return format you want

const obj = {date: 1627047000};

const date = new Date(obj.date * 1000); 

console.log(new Intl.DateTimeFormat('en-GB').format(date));
charlietfl
  • 169,044
  • 13
  • 113
  • 146