0

Problem

I'm trying to format the date from something that looks like 26/05/2015 9:14:46 AM to May 26.

I've managed to get the correct formatting on the current day, which is a good first step. However, in this case, I'm trying to format the date from the previous day, ie. the last time the API was updated regarding river levels var previousDate = result[1].Date;

I've tried var today = new Date(result[1].Date) console logs out 22/05/2015 9:31:19 AM and it returns me "undefined Nan"

scripts.js

$.ajax({
    url: 'http://opengov.brandon.ca/OpenDataService/default.aspx?format=jsonp&dataset=riverlevel&columns=Date&callback=?',
    type: 'GET',
    dataType: 'jsonp',
    success: function(result) {

      // Dates
      var currentDate = result[0].Date;
      var previousDate = result[1].Date;
      console.log(currentDate, previousDate);

      // Change date from DD/MM/YYYY to January 18
      // Create a new variable with full month names
      var monthNames = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

      var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth();

      // Puts everything above into a string
      var fixedDate = monthNames[mm] + ' ' + dd;
      $('.date').html(fixedDate); // This presents the fixed current date
10
  • The variable fixedDate seems to be working...it comes out to 'May 26'. Commented May 26, 2015 at 19:22
  • What is the value of result[1]? Commented May 26, 2015 at 19:24
  • @Samurai var previousDate = result[1].Date Will console log out: 22/05/2015 9:31:19 AM Commented May 26, 2015 at 19:27
  • @AlexPan So my first step was just to get the formatting for the current day, but where I'm stuck is applying that same formatting to var previousDate = result[1].Date Commented May 26, 2015 at 19:28
  • So, for instance previousDate = 26/05/2015 9:14:46 AM and you'd like to print May 26? Commented May 26, 2015 at 19:34

1 Answer 1

1

As pointed out the date format is not a valid one to be passed to the Date() function as a dateString, so it need to be changed to a valid one such as yyyy-mm-dd

function changeDateFormat(dt) {
    var tdt = dt.split(" ")[0].split("/");
    return tdt[2] + "-" + tdt[1] + "-" + tdt[0];
}

Then you can use:

var today = new Date(changeDateFormat(previousDate));

jsfiddle DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.