0

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>`
  );
  • What is "timestamp format"? A timestamp is any value representing a date and/or time. If you mean an ECMAScript time value (millisecond offset from 1 Jan 1970), then convert it to a Date and format it per [*How to format a JavaScript date*](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date?r=SearchResults&s=1|2041.8518). – RobG Feb 03 '22 at 23:13

2 Answers2

0

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>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • I see the dates as "03/11" but they should be "03/02". `'0' + d.getMonth() + 1` does not do what you expect. `new Date(obj.dt * 1000).toLocaleString('en-GB',{month:'2-digit',day:'2-digit'})` is less to type. :-) – RobG Feb 03 '22 at 23:21
-1

Another method

const timestamp = 1643916638401
const formattedDate = new Date(timestamp).toLocaleString('en-GB').substr(0,5);
console.log(formattedDate)
SJxD
  • 239
  • 1
  • 3
  • 10
  • The output of *toLocaleString* is implementation dependent and typically based on the default language. So this answer could return many different results, e.g. if the default language is "en-CA" it returns "2022-", for "fr" it returns "04/02", for "en" it returns "2/4/2". – RobG Feb 03 '22 at 23:16