2

I know here is a similar question but I could not apply this to my code. Don't know where to put it and different result needed.

success: function(data){
            
  var table = '';
  
  var header = '<h2>' + data.city.name + ', ' + data.city.country + '</h2>'
  
  for(var i = 0; i < data.list.length; i++){
      table += "<tr>";
      
      table += "<td>" + data.list[i].dt + "</td>";
      table += "<td><img src='img/"+data.list[i].weather[0].description+".svg'></td>";
      table += "<td>" +data.list[i].weather[0].description+ "</td>";
      table += "<td>" + Math.round(data.list[i].temp.day) + "&deg;</td>";           
      
      table += "</tr>";
  }
  
  $("#forecastWeather").html(table);
  $("#header").html(header);
  
  $("#city").val('');
  }
});

I am making a weather app using Open Weather Map Forecast 16. All works fine but I cant figure out how to convert the unix timestamp in my code to the day of the week. Here is the line in my JavaScript code where I add the date to the table:

table += "<td>" + data.list[i].dt + "</td>";

This gives my number like: 1522666800. How do I get it to show a weekday?

James Miller
  • 121
  • 2
  • 12
  • Possible duplicate of [Convert a Unix timestamp to time in JavaScript](https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript) – bugs Apr 02 '18 at 09:36

2 Answers2

4

to get the day number from the week use:

new Date(data.list[i].dt * 1000).getDay()
AlexScr
  • 442
  • 2
  • 10
  • @JamesMiller it returns the day number, please see [getDay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay) – AlexScr Apr 02 '18 at 09:48
4

See answer for this question: Day Name from Date in JS

Solution:

var i = 0;
var data = { list: [ { dt: 1522666800 } ] };

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; 
var dayNum = new Date(data.list[i].dt * 1000).getDay();
var result = days[dayNum];
console.log(result);
ollazarev
  • 1,076
  • 8
  • 26