0

I am using OpenWeatherMap API and I am trying to retrieve the LastUpdated property.

Let me rephrase, I can retrieve the LastUpdated property, but with JSON format it comes as a timestamp.

How can I convert that timestamp to a normal date/time to display to the user?

I have done some research and downloaded Moment.js, but when I run the page, I get an error saying:

Error: Object doesn't support property or method 'format'

Here is my code:

<script src="~/Scripts/moment.js"></script>
<script>
    $(document).ready(function () {
        var request = $.ajax({
            url: "http://api.openweathermap.org/data/2.5/weather",
            method: "GET",
            data: { id: '4142290', appid: 'myapikey', units: 'imperial' },
            success: function (response) {
                console.log(response);
                var weatherIcon = response.weather[0].icon;
                var weatherDescription = response.weather[0].description;
                var weatherTemp = response.main.temp;
                var lastUpdated = response.dt;
                var formatted = lastUpdated.format("dd.mm.yyyy hh:MM:ss");

                var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png";
                document.getElementById('Weather-Image').src = iconUrl;
                document.getElementById('Weather-Description').innerHTML = "[" + weatherDescription + "]";
                document.getElementById('Weather-Temp').innerHTML = weatherTemp;
                document.getElementById('Weather-Updated').innerHTML = formatted;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText)
            }
        });
    });
</script>

Any help is appreciated.

Grizzly
  • 5,873
  • 8
  • 56
  • 109
  • Have a check at: http://stackoverflow.com/questions/19485353/function-to-convert-timestamp-to-human-date-in-javascript, the best solution is given by RobG, who won 41 upvote – CY_ Dec 09 '16 at 15:20

1 Answers1

2

You're trying to call Moment.js' format method on a timestamp, rather than an instance of Moment

You first need to parse the returned timestamp and then format it in the style you require.

var formatted = moment(response.dt).format("dd.mm.yyyy hh:MM:ss");

Assuming that response.dt is a format supported by the parsing function of moment.js (docs)

Jordan Burnett
  • 1,799
  • 8
  • 11