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";
console.log(strtoUTCtoLocal(dateStr));

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() + ":" + 
                 d2.getMinutes().toString();
}

Answers:

Answer

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

    document.write(parseDate(s));

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.