Javascript Date time String to UTC date time and UTC to Local Date time

i needed to convert string to UTC date , and then UTC date to local date.

here is my code :

var dateStr = "9/8/2015 12:44:00 PM";

function strtoUTCtoLocal(dateStr)
    var d1 = new Date(dateStr).toUTCString();
    var d2= new Date(d1);

     return      "0" + (d2.getMonth()+1).toString().slice(-2) + "/" +
                 "0" + d2.getDate().toString().slice(-2) + "/" +
                 d2.getFullYear().toString() + " " +
                 d2.getHours().toString() + ":" + 



Parsing date strings should be done manually since Date.parse is inconsistent across browsers. Assuming your format is d/m/y, you can parse it to a UTC time using the following:

    var s = '9/8/2015 12:44:00 PM';

    function parseDate(s) {
      var b = s.split(/\D+/);
      var ap = /pm$/i.test(s)? 12 : 0;
      return new Date(Date.UTC(b[2], b[1]-1, b[0], ((b[3]%12) + ap), b[4], b[5]));


If you need to validate the date, you'll need an extra line of code.

Note that by default, strings without a timezone are generally parsed as local (except for ISO 8601 format strings in ES5 using Date.parse, but ECMAScript 2015 parses them as local, which was changed to UTC with ECMAScript 2016).


I'd recommend checking out momentjs ( It's an awesome library that handles all sorts of date operations like this.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.