Ashima
Ashima

Reputation: 4834

Convert UTC to standard date time format using javascript

How can I convert a UTC time into proper date - time format using Javascript?

This is what I want to do

var d = new Date("2014-01-01");
var new_d = d.toUTC(); // 1388534400000
var old_d = function(new_d){
    // return "2014-01-01" // how can i get this? 
}

Now How, can i get orignal date - 2014-01-01 from 1388534400000?

****Also, Please note that when i do this --- new Date(1388534400000); it gives date 1 day less. That is, instead of giving Jan 01 2014, it gives Dec 31 2013. But, I want Jan 01 2014.****

Is there any method to do the opposite of toUTC() method?

// _________ For those whose toUTC() doesnt work

"toUTC" method works in console of my chrome See screen shot below

enter image description here

Upvotes: 0

Views: 2207

Answers (3)

André Snede
André Snede

Reputation: 10055

The problem lies with the way you instantiate the Date. Javascript interpretes the hyphens as an utc date, and slashes as local dates.

Giving the results that mark Explains.

var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date

But to translate a date back to your starting point string, you can do the following.

function toDateString(utcMillis){
    var date = new Date(utcMillis);
    d = date.getDate();
    m = date.getMonth() +1;
    y = date.getFullYear();
    return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}

function addLeadingZero(n, length){
   n = n+'';
   if(n.length<length)
      return addLeadingZero('0'+n, length--);
   else
      return n;
}

If you find yourself with a UTC date, you can still do this:

function toUTCDateString(utcMillis){
    var date = new Date(utcMillis);
    d = date.getUTCDate();
    m = date.getUTCMonth() +1;
    y = date.getUTCFullYear();
    return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}

To play around with it, and see it for yourself, see this Fiddle:

Upvotes: 1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241900

When you pass a string containing hyphens to the Date constructor, it will treat that as UTC. And if you don't pass a time, it will consider it to be midnight. If you are in a time zone that is behind UTC (such as in most of the Americas), you will see the wrong local time conversion.

Here's a screenshot of my chrome dev console, so you can see what I mean

screenshot

If I pass slashes instead:

screenshot

Consider using moment.js - which will accept a format parameter that will help you avoid this issue.

Upvotes: 2

khalid13
khalid13

Reputation: 2847

Try using the following:

new Date(new_d); 

Upvotes: 1

Related Questions