Home > Blockchain >  Convert date in timestamp to DD/MM format inside forEach
Convert date in timestamp to DD/MM format inside forEach

Time:02-04

Is possible to convert date in timestamp format to get day and month in format DD/MM ?

 result.forEach(obj =>
    html  = `Temperature: ${obj.temp} ºC<br>
    Day: ${obj.dt}<br>
    Description: ${obj.description}<br>
    ${iconCodes[obj.icon]}<br><br>`
  );

CodePudding user response:

I saw from your previous question that obj.dt is a timestamp. It's a normal timestamp (number of seconds since the epoch) so we'll need to multiiple by 1000 to make it a timestamp javascript understands (it counts in millliseconds). You can easily modify that into the format you want by converting it into a date object, then using methods to extract the day and month. To keep everything to 2 digits, I used slice()

let result = [
  {
    dt: 1643884851,
    temp: 8.11,
    description: 'few clouds',
    icon: '02d'
  },
  {
    dt: 1643889600,
    day: 9.56,
    description: 'scattered clouds',
    icon: '03d'
  }
]

const getTimeFrom = d => {
  d = new Date(d * 1000);
  console.log(d)
  let day = ('0'   d.getDate()).slice(-2);
  let month = ('0'   d.getMonth()   1).slice(-2);
  return `${day}/${month}`;
}

html = '';
result.forEach(obj =>
    html  = `Temperature: ${obj.temp} ºC<br>
    Day: ${getTimeFrom(obj.dt)}<br>
    Description: ${obj.description}<br>
    ${obj.icon}<br><br>`
  );
  
  document.querySelector('#output').innerHTML = html
<div id='output'></div>

CodePudding user response:

Another method

const timestamp = 1643916638401
const formattedDate = new Date(timestamp).toLocaleString().substr(0,5);
console.log(formattedDate)

  •  Tags:  
  • Related