RockOnGom
RockOnGom

Reputation: 3961

Convert UTC datetime to local datetime

I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is

Fri Mar 8 23:12:27 UTC+0200 2013

Also my JavaScript code is

var time = Date(param_time);//param_time is /Date(1362866006646)/

And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.

http://ejohn.org/files/pretty.js

How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.

Upvotes: 2

Views: 14766

Answers (4)

Erick Wendel
Erick Wendel

Reputation: 482

var day = 10;
var month = 04;
var year = 2015;

var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000

var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)

Upvotes: 0

Eliasz Kubala
Eliasz Kubala

Reputation: 3904

  var timezone = "UTC+01:30";
  var start = new Date();
  if(timezone != "UTC"){
      timezone = timezone.replace(/UTC/g,"");
      znak = timezone.charAt(0);
      timezone = timezone.replace(/[+|-]/g,"");
      timezone = timezone.split(":");
      //var start = new Date(start.toString() + " " + timezone);e.
      //alert(start.toString());
      if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000)   );
      if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000)   );
  }
  var hours = start.getUTCHours();
  var minutes = start.getUTCMinutes();
  var seconds = start.getUTCSeconds();

Upvotes: 1

Panayot Karabakalov
Panayot Karabakalov

Reputation: 3179

I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.

However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:

function UTCToLocalTime(d) {
    var timeOffset = -((new Date()).getTimezoneOffset()/60);
    d.setHours(d.getHours() + timeOffset);
    return d;
}

var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013

//p.s. or...
function UTCToLocalTime2(d)
{
  return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}

Upvotes: 1

Zeta
Zeta

Reputation: 105945

In order to format your Date correctly use toISOString():

var time = param_time.toISOString();

Note that param_time needs to be a valid Date object.

References

Upvotes: 6

Related Questions