0

I'm running into an issue in javascript where certain dates are in a dd/mm/yyyy format and others are in yyyy-dd-mmT00000. I want them in dd/mm/yyyy but the problem is when I run through my code, I call the format method and it is specifically for dates like "2018-02-06T00:00:00". When I get a date like 02/06/2018, it runs through the format function and messes it up. Is there anyway I could make a conditional saying if (date is formatted) { dont format }, or could I change my format method in any way?

This is the format function:

formatDate: function (date) {
    for (var i = 0; i < date.length; i++) {
        var day = date.substring(8);
        if (day.charAt(0) == 0) {
            day = day.substring(1);
        }
        var month = date.substring(5, 7);
        if (month.charAt(0) == 0) {
            month = month.substring(1);
        }
        var year = date.substring(0, 4);
        var finalDateString = month + "/" + day + "/" + year;
    }
    return finalDateString;
}

This is part of the create function I use to create a table to store the information:

  if (todos[i].progress != 100) {
    todos[i].completed_date = "";
    var dateDisplay = todos[i].completed_date;
 }
  if (todos[i].progress == 100) {
    var dateDisplay = todos[i].completed_date;

    if (dateDisplay instanceof Date) {
       dateDisplay = dateDisplay.toLocaleDateString();
    } else {
       dateDisplay = dateDisplay.slice(0, 10);
       dateDisplay = formatDate(dateDisplay);
     }
  }
Patrick S
  • 65
  • 1
  • 2
  • 13
  • Couldn't you check the date format as described here? https://stackoverflow.com/questions/7388001/javascript-regex-to-validate-date-format – Marc Feb 07 '18 at 14:46
  • @Marc I have no clue what that is but I'll check it out thanks. – Patrick S Feb 07 '18 at 14:49
  • Possible duplicate of [Javascript - Regex to validate date format](https://stackoverflow.com/questions/7388001/javascript-regex-to-validate-date-format) – HMR Feb 07 '18 at 14:58
  • I would [parse it as a `Date` object](https://stackoverflow.com/q/5619202/215552), then [format the date](https://stackoverflow.com/q/1056728/215552), rather than guessing at string formats. – Heretic Monkey Feb 07 '18 at 15:46
  • @MikeMcCaughan what I ended up doing was throwing another if statement in the else statement saying if (dateDisplay.length > 10) { dateDisplay.slice()...formatDate()) }. It fixed my issue and hasnt caused any other issues, atleast yet. Thanks for the answer tho – Patrick S Feb 07 '18 at 15:52
  • @MikeMcCaughan—to implement a parser you must know the format of the string you're parsing, otherwise you're leaving it to the parser to guess. ;-) – RobG Feb 07 '18 at 23:22

0 Answers0