[javascript] Converting a string to a date in JavaScript

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

This question is related to javascript date type-conversion date-parsing

The answer is


                //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);

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)

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().


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());

Yet another way to do it is to build a regex with named capture groups over the format string and then use that regex to extract the day, month and year from the date string:

_x000D_
_x000D_
function parseDate(dateStr, format) {_x000D_
  const regex = format.toLocaleLowerCase()_x000D_
    .replace(/\bd+\b/, '(?<day>\\d+)')_x000D_
    .replace(/\bm+\b/, '(?<month>\\d+)')_x000D_
    .replace(/\by+\b/, '(?<year>\\d+)')_x000D_
  _x000D_
  const parts = new RegExp(regex).exec(dateStr) || {};_x000D_
  const { year, month, day } = parts.groups || {};_x000D_
  return parts.length === 4 ? new Date(year, month-1, day) : undefined;_x000D_
}_x000D_
_x000D_
const printDate = x => console.log(x ? x.toLocaleDateString() : x);_x000D_
_x000D_
printDate(parseDate('05/11/1896', 'dd/mm/YYYY'));_x000D_
printDate(parseDate('07-12-2000', 'dd-mm-yy'));_x000D_
printDate(parseDate('07:12:2000', 'dd:mm:yy'));_x000D_
printDate(parseDate('2017/6/3', 'yy/MM/dd'));_x000D_
printDate(parseDate('2017-6-15', 'y-m-d'));_x000D_
printDate(parseDate('2015 6 25', 'y m d'));_x000D_
printDate(parseDate('2015625', 'y m d')); // bad format
_x000D_
_x000D_
_x000D_


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","-")

You can also do: mydate.toLocaleDateString();


_x000D_
_x000D_
function dateConvertor(date){
   var options = { weekday: "long",  
                    year: "numeric",  
                    month: "short",  
                    day: "numeric" };  

   var newDateFormat = new Date(date).toLocaleDateString("en-US", options); 
   var newTimeFormat = new Date(date).toLocaleTimeString();  
   var dateAndTime = newDateFormat +' ' + newTimeFormat        
  return dateAndTime
}


console.log(dateConvertor("2021-01-19T18:30:00.000Z"));
_x000D_
_x000D_
_x000D_


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.


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

Unfortunately I found out that

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

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

The bulletproof solution is the following:

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


You Can try this:

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


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"


I wrote a reusable function that i use when i get date strings from the server.
you can pass your desired delimiter( / - etc..) that separates the day month and year in order to use the split() method.
you can see & test it on this working example.

<!DOCTYPE html>
<html>
  <head>
    <style>
    </style>
  </head>
  <body>
    <div>
      <span>day:
      </span> 
      <span id='day'>
      </span>
    </div>
    <div>
      <span>month:
      </span> 
      <span id='month'>
      </span>
    </div>
    <div>
      <span>year:
      </span> 
      <span id='year'>
      </span>
    </div>
    <br/>
    <input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
    <span>28/10/1980
    </span>
    <script>
      function convert(delimiter,dateString)
      {
        var splitted = dateString.split('/');
        // create a new date from the splitted string 
        var myDate = new Date(splitted[2],splitted[1],splitted[0]);
        // now you can access the Date and use its methods 
        document.getElementById('day').innerHTML = myDate.getDate();
        document.getElementById('month').innerHTML = myDate.getMonth();
        document.getElementById('year').innerHTML = myDate.getFullYear();
      }
    </script>
  </body>
</html>

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!!!


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;
}

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

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}

This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.

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 year = parseInt(dateItems[yearIndex]); 
        // adjust for 2 digit year
        if (year < 100) { year += 2000; }
        var month=parseInt(dateItems[monthIndex]);
        month-=1;
        var formatedDate = new Date(year,month,dateItems[dayIndex]);
        return formatedDate;
}

stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")

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", "/")

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;

}


moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.

You could add a 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

Some display examples

let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL')) 
// output: "3 months ago | February 1, 2019"

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

Recommendation: I recommend to use 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 date from a simple string to date but I think that is a hard work to support all formats and variations of dates.


_x000D_
_x000D_
var a = "13:15"_x000D_
var b = toDate(a, "h:m")_x000D_
//alert(b);_x000D_
document.write(b);_x000D_
_x000D_
function toDate(dStr, format) {_x000D_
  var now = new Date();_x000D_
  if (format == "h:m") {_x000D_
    now.setHours(dStr.substr(0, dStr.indexOf(":")));_x000D_
    now.setMinutes(dStr.substr(dStr.indexOf(":") + 1));_x000D_
    now.setSeconds(0);_x000D_
    return now;_x000D_
  } else_x000D_
    return "Invalid Format";_x000D_
}
_x000D_
_x000D_
_x000D_


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");

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();

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; 
}

Performance

Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.

Conclusions

  • Solution new Date (Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestamp
  • Solution new Date (Ad) is ~10x faster than parseDate (Ed)
  • Solution Date.parse(Bd) is fastest if wee need to get timestamp from ISO date on all browsers

enter image description here

Details

I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate (Ed) use new Date(0) and manually set UTC date components.

_x000D_
_x000D_
let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000';    // timestamp

let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);

let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();

log = (n,d) => console.log(`${n}: ${+d} ${d}`);

console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);



function parseDate(dateStr) {
  let [year,month,day] = dateStr.split(' ')[0].split('-');
  let d=new Date(0);
  d.setUTCFullYear(year);
  d.setUTCMonth(month-1);
  d.setUTCDate(day)
  return d;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>

This snippet only presents used soultions  
_x000D_
_x000D_
_x000D_

Results for chrome

enter image description here


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.


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));

Just new Date(st);

Assuming that it's the proper format.


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

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);

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift

Examples related to date-parsing

Format date with Moment.js Converting a string to a date in JavaScript