Nodejs String to Date Convert toDate()

Here you can find the source of toDate()

Method Source Code

/**/*from w  w w  .j  a  va 2  s  .com*/
 * String#toDate() -> Date
 *
 * Returns the current String as an instance of Date.
**/
String.prototype.toDate = function()
{
  var date, parts, year, month, day, hours, minutes, seconds, ms;

  // Check for ISO 8601 dates
  if (parts = this.match(/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.([0-9]{1,3}))?(Z|([-+0-9:]{6}))$/))
  {
    date = Date.parse(this);

    if (isNaN(date)) // ISO-8601 Parsing Unsupported...
    {
      year    = parts[1];
      month   = parts[2];
      day     = parts[3];
      hours   = parts[4];
      minutes = parts[5];
      seconds = parts[6];
      ms      = parts[8] || 0;
      tz      = parts[10] || false;

      if (tz)
      {
        var dateString = Date.shortMonthNames[month - 1] + " " + day + ", " + year + " " + hours + ":" + minutes + ":" + seconds + " GMT" + tz.gsub(":", "");
        date = new Date(Date.parse(dateString));
      }
      else
        date = new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds, ms));
    }
    else
      date = new Date(date);
  }

  // Pass-through all other date formats...
  else
    date = new Date(this.toString());

  return date;
}

Related

  1. toDate()
    String.prototype.toDate = function() {
        return new Date(this.slice(0,15));
    };
    
  2. toDate()
    String.prototype.toDate = () =>{
        var from = $(this).val().split("/");
        var f = new Date(from[2], from[1] - 1, from[0]);
        return f;
    
  3. toDate(dateIsOmittable, monthIsOmittable)
    String.THROW_WHEN_INVALID_DATE = true
    String.prototype.toDate = function(dateIsOmittable, monthIsOmittable) {
        var date = null;
        var str = "0000-00-00";
        if (/^\d{4}-\d{2}-\d{2}$/.test(this))
            str = new String(this);
        else if (dateIsOmittable && /^\d{4}-\d{2}$/.test(this))
            str = this + "-01";
        else if (dateIsOmittable && monthIsOmittable && /^\d{4}$/.test(this))
    ...
    
  4. toDate(pattern = 'YYYY-MM-DD')
    String.prototype.toDate = function (pattern = 'YYYY-MM-DD') {
        let date = new Date()
        if (pattern.indexOf("YYYY") > -1) {
            const yearIndex = pattern.indexOf("YYYY")
            date.setFullYear(this.substring(yearIndex,yearIndex+4))
        if(pattern.indexOf("MM")>-1){
            const monthIndex = pattern.indexOf("MM")
            date.setMonth(this.substring(monthIndex,monthIndex+2)-1)
    ...
    
  5. toDate(str)
    String.prototype.toDate = function(str) {
        var m = this.match(/(\d+)-(\d+)-(\d+)\s+(\d+):(\d+):(\d+)/);
        return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]);