当前位置 : 首页 » 互动问答 » 正文

Converting a string to a date in JavaScript

分类 : 互动问答 | 发布时间 : 2011-04-11 17:21:18 | 评论 : 30 | 浏览 : 1251812 | 喜欢 : 463

How can I convert a string to a date in JavaScript?

var st = "date in some format"
var dt = new date();

var dt_st= //st in date format same as dt

回答(30)

  • 1楼
  • The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

    Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

    But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

    To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

    To display a date in UTC, use .toUTCString(),
    to display a date in user's local time, use .toString().

    More info on MDN | Date and this answer.

    For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


    Alternate method - use an appropriate library:

    You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

  • 2楼
  • Unfortunately I found out that

    var mydate = new Date('2014-04-03');
    console.log(mydate.toDateString());

    returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.

    The bulletproof solution is the following:

    var parts ='2014-04-03'.split('-');
    // Please pay attention to the month (parts[1]); JavaScript counts months from 0:
    // January - 0, February - 1, etc.
    var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
    console.log(mydate.toDateString());

  • 3楼
  • var st = "26.04.2013";
    var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
    var dt = new Date(st.replace(pattern,'$3-$2-$1'));
    

    And the output will be:

    dt => Date {Fri Apr 26 2013}
    
  • 4楼
  • function stringToDate(_date,_format,_delimiter)
    {
                var formatLowerCase=_format.toLowerCase();
                var formatItems=formatLowerCase.split(_delimiter);
                var dateItems=_date.split(_delimiter);
                var monthIndex=formatItems.indexOf("mm");
                var dayIndex=formatItems.indexOf("dd");
                var yearIndex=formatItems.indexOf("yyyy");
                var month=parseInt(dateItems[monthIndex]);
                month-=1;
                var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
                return formatedDate;
    }
    
    stringToDate("17/9/2014","dd/MM/yyyy","/");
    stringToDate("9/17/2014","mm/dd/yyyy","/")
    stringToDate("9-17-2014","mm-dd-yyyy","-")
    
  • 5楼
  • Pass it as an argument to Date():

    var st = "date in some format"
    var dt = new Date(st);
    

    You can access the date, month, year using, for example: dt.getMonth().

  • 6楼
  • new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"

    See that 0 for month gives you January

  • 7楼
  • If you can use the terrific moment library (e.g. in an Node.js project) you can easily parse your date using e.g.

    var momentDate = moment("2014-09-15 09:00:00");
    

    and can access the JS date object via

    momentDate ().toDate();
    
  • 8楼
  • moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.

    You could add string date and format.

    moment("12-25-1995", "MM-DD-YYYY");
    

    And you could check if a date is valid.

    moment("not a real date").isValid(); //Returns false
    

    See documentation http://momentjs.com/docs/#/parsing/string-format/

    Recommendation: I recommend using a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily a date from a simple string to date but I think that is a hard work to support all formats and variations of dates.

  • 9楼
  • For those who are looking for a tiny and smart solution:

    String.prototype.toDate = function(format)
    {
      var normalized      = this.replace(/[^a-zA-Z0-9]/g, '-');
      var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
      var formatItems     = normalizedFormat.split('-');
      var dateItems       = normalized.split('-');
    
      var monthIndex  = formatItems.indexOf("mm");
      var dayIndex    = formatItems.indexOf("dd");
      var yearIndex   = formatItems.indexOf("yyyy");
      var hourIndex     = formatItems.indexOf("hh");
      var minutesIndex  = formatItems.indexOf("ii");
      var secondsIndex  = formatItems.indexOf("ss");
    
      var today = new Date();
    
      var year  = yearIndex>-1  ? dateItems[yearIndex]    : today.getFullYear();
      var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
      var day   = dayIndex>-1   ? dateItems[dayIndex]     : today.getDate();
    
      var hour    = hourIndex>-1      ? dateItems[hourIndex]    : today.getHours();
      var minute  = minutesIndex>-1   ? dateItems[minutesIndex] : today.getMinutes();
      var second  = secondsIndex>-1   ? dateItems[secondsIndex] : today.getSeconds();
    
      return new Date(year,month,day,hour,minute,second);
    };
    

    Example:

    "22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
    "2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
    
  • 10楼
  • If you want to convert from the format "dd/MM/yyyy". Here is an example:

    var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    var arrayDate = stringDate.match(pattern);
    var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
    

    This solution works in IE versions less than 9.

  • 11楼
  • Timestamps should be casted to a Number

    var ts = '1471793029764';
    ts = Number(ts); // cast it to a Number
    var date = new Date(ts); // works
    
    var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
    
  • 12楼
  • Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:

    var str = 'Sun Apr 25, 2010 3:30pm',
        timestamp;
    
    timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
    
    if(str.match(/pm$/i) >= 0) {
        timestamp += 12 * 60 * 60 * 1000;
    }
    
  • 14楼
  • Just new Date(st);

    Assuming that it's the proper format.

  • 15楼
  • Convert to format pt-BR:

        var dateString = "13/10/2014";
        var dataSplit = dateString.split('/');
        var dateConverted;
    
        if (dataSplit[2].split(" ").length > 1) {
    
            var hora = dataSplit[2].split(" ")[1].split(':');
            dataSplit[2] = dataSplit[2].split(" ")[0];
            dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
    
        } else {
            dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
        }
    

    I hope help somebody!!!

  • 16楼
  • I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object. https://jsfiddle.net/Sushil231088/q56yd0rp/

    "17/9/2014".toDate("dd/MM/yyyy", "/")
    
  • 17楼
  • For сonverting string to date in js i use http://momentjs.com/

    moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
    moment().format('dddd');                    // Sunday
    moment().format("MMM Do YY");               // Aug 16th 15
    moment().format('YYYY [escaped] YYYY');     // 2015 escaped 2015
    moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
    moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
    moment().startOf('day').fromNow();        // 16 hours ago
    moment().endOf('day').fromNow();          // in 8 hours
    
  • 18楼
  • Yet another way to do it:

    String.prototype.toDate = function(format) {
        format = format || "dmy";
        var separator = this.match(/[^0-9]/)[0];
        var components = this.split(separator);
        var day, month, year;
        for (var key in format) {
            var fmt_value = format[key];
            var value = components[key];
            switch (fmt_value) {
                case "d":
                    day = parseInt(value);
                    break;
                case "m":
                    month = parseInt(value)-1;
                    break;
                case "y":
                    year = parseInt(value);
            }
        }
        return new Date(year, month, day);
    };
    a = "3/2/2017";
    console.log(a.toDate("dmy"));
    // Date 2017-02-03T00:00:00.000Z
    
  • 19楼
  • I made this function to convert any Date object to a UTC Date object.

    function dateToUTC(date) {
        return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    }
    
    
    dateToUTC(new Date());
    
  • 20楼
  • var date = new Date(year, month, day);
    

    or

    var date = new Date('01/01/1970');
    

    date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.

  • 21楼
  • If you need to check the contents of the string before converting to Date format:

    // Convert 'M/D/YY' to Date()
    mdyToDate = function(mdy) {
      var d = mdy.split(/[\/\-\.]/, 3);
    
      if (d.length != 3) return null;
    
      // Check if date is valid
      var mon = parseInt(d[0]), 
          day = parseInt(d[1]),
          year= parseInt(d[2]);
      if (d[2].length == 2) year += 2000;
      if (day <= 31 && mon <= 12 && year >= 2015)
        return new Date(year, mon - 1, day);
    
      return null; 
    }
    
  • 22楼
  • var a = "13:15"
    var b = toDate(a, "h:m")
    alert(b);
    
    function toDate(dStr, format) {
      var now = new Date();
      if (format == "h:m") {
        now.setHours(dStr.substr(0, dStr.indexOf(":")));
        now.setMinutes(dStr.substr(dStr.indexOf(":") + 1));
        now.setSeconds(0);
        return now;
      } else
        return "Invalid Format";
    }

  • 23楼
  • You Can try this:

    function formatDate(userDOB) {
      const dob = new Date(userDOB);
    
      const monthNames = [
        'January', 'February', 'March',
        'April', 'May', 'June', 'July',
        'August', 'September', 'October',
        'November', 'December'
      ];
    
      const day = dob.getDate();
      const monthIndex = dob.getMonth();
      const year = dob.getFullYear();
    
      // return day + ' ' + monthNames[monthIndex] + ' ' + year;
      return `${day} ${monthNames[monthIndex]} ${year}`;
    }
    
    console.log(formatDate('1982-08-10'));

  • 24楼
  • ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.

    This is a great resource to figure out which datestring format you should use:

    http://dygraphs.com/date-formats.html

    Yes, that means that your datestring could be as simple as as opposed to

    "2014/10/13 23:57:52" instead of "2014-10-13 23:57:52"

  • 25楼
  •                 //little bit of code for Converting dates 
    
                    var dat1 = document.getElementById('inputDate').value;
                    var date1 = new Date(dat1)//converts string to date object
                    alert(date1);
                    var dat2 = document.getElementById('inputFinishDate').value;
                    var date2 = new Date(dat2)
                    alert(date2);
    
  • 26楼
  • use this code : (my problem was solved with this code)

    function dateDiff(date1, date2){
    var diff = {}                           // Initialisation du retour
    var tmp = date2 - date1;
    
    tmp = Math.floor(tmp/1000);             // Nombre de secondes entre les 2 dates
    diff.sec = tmp % 60;                    // Extraction du nombre de secondes
    
    tmp = Math.floor((tmp-diff.sec)/60);    // Nombre de minutes (partie entière)
    diff.min = tmp % 60;                    // Extraction du nombre de minutes
    
    tmp = Math.floor((tmp-diff.min)/60);    // Nombre d'heures (entières)
    diff.hour = tmp % 24;                   // Extraction du nombre d'heures
    
    tmp = Math.floor((tmp-diff.hour)/24);   // Nombre de jours restants
    diff.day = tmp;
    
    return diff;
    

    }

  • 27楼
  • I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser

        function parseDateTime(datetime) {
                var monthNames = [
                    "January", "February", "March",
                    "April", "May", "June", "July",
                    "August", "September", "October",
                    "November", "December"
                  ];
                if(datetime.split(' ').length == 3){
                    var date = datetime.split(' ')[0];
                    var time = datetime.split(' ')[1].replace('.00','');
                    var timearray = time.split(':');
                    var hours = parseInt(time.split(':')[0]);
                    var format = datetime.split(' ')[2];
                    var bits = date.split(/\D/);
                    date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                    var day = date.getDate();
                    var monthIndex = date.getMonth();
                    var year = date.getFullYear();
                    if ((format === 'PM' || format === 'pm') && hours !== 12) {
                        hours += 12;
                        try{  time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
                    } 
                    var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                    return formateddatetime;
                }else if(datetime.split(' ').length == 2){
                    var date = datetime.split(' ')[0];
                    var time = datetime.split(' ')[1];
                    var bits = date.split(/\D/);
                    var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                    var day = datetimevalue.getDate();
                    var monthIndex = datetimevalue.getMonth();
                    var year = datetimevalue.getFullYear();
                    var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                    return formateddatetime;
                }else if(datetime != ''){
                    var bits = datetime.split(/\D/);
                    var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                    return date;
                }
                return datetime;
            }
    
        var date1 = '2018-05-14 05:04:22 AM';   // yyyy-mm-dd hh:mm:ss A
        var date2 = '2018/05/14 05:04:22 AM';   // yyyy/mm/dd hh:mm:ss A
        var date3 = '2018/05/04';   // yyyy/mm/dd
        var date4 = '2018-05-04';   // yyyy-mm-dd
        var date5 = '2018-05-14 15:04:22';   // yyyy-mm-dd HH:mm:ss
        var date6 = '2018/05/14 14:04:22';   // yyyy/mm/dd HH:mm:ss
    
        console.log(parseDateTime(date1))
        console.log(parseDateTime(date2))
        console.log(parseDateTime(date3))
        console.log(parseDateTime(date4))
        console.log(parseDateTime(date5))
        console.log(parseDateTime(date6))
    
    **Output---**
    Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
    Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
    Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
    Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
    Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
    Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
    
  • 28楼
  • You can using regex to parse string to detail time then create date or any return format like :

    //example : let dateString = "2018-08-17 01:02:03.4"
    
    function strToDate(dateString){
        let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
      , [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
      , dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
      return dateObject;
    }
    alert(strToDate(dateString));
    
  • 29楼
  • You should make your own function. This will be more convenient. Here is the example. You can modify it according to your requirment.

        const  dateFormater = function(dt, seprator){
    
            let monthStore = ["January","February","March","April","May","June", "July","August","September","October","November","December"];
            
    
            const date = dt.split(seprator);
            //below choose month, day, year in the same order you passed in function as string
            const month = monthStore[date[0]-1]; 
            const day = date[1];
            const year = date[2];
            const dateToReturn = month+' '+day+' '+year // you can change order to print as required
    
            return(dateToReturn)
        }
    
    var formatedDate = dateFormater('12/11/2018','/'); // /m/d/y
    var formatedDate2 = dateFormater('09-10-2018','-');
    
    console.log(formatedDate);
    console.log(formatedDate2 )

  • 30楼
  • use this format....

    //get current date in javascript
    
      var currentDate = new Date();
    
    
    // for getting a date from a textbox as string format
    
       var newDate=document.getElementById("<%=textBox1.ClientID%>").value;
    
    // convert this date to date time
    
       var MyDate = new Date(newDate);
    

相关阅读:

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How to convert string to char array in C++?

How do I replace a character at a particular index in JavaScript?

JavaScript file upload size validation

Converting a string to a date in JavaScript