2

I want to parse dates (string date format to javascript date format), but I have various string date format like YYYY-MM-DD, DD-MM-YYYY and 'DD/MM/YYYY' and so..

Is there any generic procedure or way to convent from these string date format to javascript date format?

2
  • This question is numerous times better stated than the one pointed at!—Actually, the one pointed at is totally out of shape and should be closed. Commented Feb 11, 2020 at 13:57
  • This question is numerous times better stated than the one pointed at!—Actually, the one pointed at is closed for being unclear what is asked! Commented Feb 12, 2020 at 17:10

4 Answers 4

2

These are two libraries that I use for that:

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

1 Comment

Just two? There is also XDate, fecha.js, date-fns, Later.js, Countdown.js, Cubism.js (D3 plugin), js-joda, … ;-)
1

Here userFormat string could be in these format 'DD-MM-YYYY', 'YYYY-MM-DD', 'DD/MM/YYYY' etc..

function parseDate(dateString, userFormat) {
    var delimiter, theFormat, theDate, month, date, year;
    // Set default format if userFormat is not provided
    userFormat = userFormat || 'yyyy-mm-dd';

    // Find custom delimiter by excluding
    // month, day and year characters
    delimiter = /[^dmy]/.exec(userFormat)[0];

    // Create an array with month, day and year
    // so we know the format order by index
    theFormat = userFormat.split(delimiter);

    //Create an array of dateString.
    theDate = dateString.split(delimiter);
    for (var i = 0, len = theDate.length; i < len; i++){
      //assigning values for date, month and year based on theFormat array.
      if (/d/.test(theFormat[i])){
        date = theDate[i];
      }
      else if (/m/.test(theFormat[i])){
        month = parseInt(theDate[i], 10) - 1;
      }
      else if (/y/.test(theFormat[i])){
        year = theDate[i];
      }
    }
    return (new Date(year, month, date));
}

1 Comment

wow..its very very generic procedure..thats what i wanted actually great thanks.
0

Just go get datejs.

http://www.datejs.com/

...and never bother with writing your own Javascript date functions again.

Comments

-1
function dateParsing(toDate, dateFormat) {
    var dt = Date.parseInvariant(todate, dateFormat); // pass date and your desired format e.g yyyy/M/dd            
    alert(dt); // to check date
}

2 Comments

Date.parseInvariant() is not a Javascript function.
Actually, Date.parseInvariant in an JScript (Microsoft-only) "Date Type Extensions". "Date extensions are part of the Microsoft Ajax Library and add functionality to the JavaScript Date object." msdn.microsoft.com/en-us/ie/bb310850(v=vs.94)