Alexandre
Alexandre

Reputation: 759

Convert specific datetime with specific timezone in javascript

How can i convert this datetime format:

2013-05-04 17:25:00

To a timezone that i can specify. Something like this:

convertTimeZone('2013-05-04 17:25:00', '+3');

And return the following datetime with the specified timezone?

Upvotes: 1

Views: 1386

Answers (2)

Xotic750
Xotic750

Reputation: 23472

Take a look at Moments.js

then you could do something like this (just an example may not match exactly what you are asking)

var date1 = moment.utc("2013-05-04 17:25:00").format("YYYY-MM-DDTHH:mm:ss");

console.log(date1.toString());

var date2 = moment.utc(date1).add("hours", 3).format("YYYY-MM-DDTHH:mm:ss");

console.log(date2.toString());

which will output

2013-05-04T17:25:00
2013-05-04T20:25:00 

On jsfiddle

Upvotes: 0

Brombomb
Brombomb

Reputation: 7076

Hopefully this is enough to get you started

// time should be a string in your format
// offset should be an int (i.e. 3 or -3)
function convertTimeZone(time, offset) {
    time = time.replace('-','/');
    return new Date(time).addHours(parseInt(offset, 10));
}

To be called as such

convertTimeZone('2013-05-04 17:25:00', 3);
convertTimeZone('2013-05-04 17:25:00', -3);

Javascript doesn't like - so replace them with / which it will accept. None of this uses jquery, this is just basic javascript.

Upvotes: 2

Related Questions