Muayad Salah
Muayad Salah

Reputation: 711

Javascript Date(): How to convert the local date to GMT

I'm sending the server time object with zero date, the sent date is: Thu Jan 01 1970 01:02:01 GMT+0200 How can I convert it to GMT+0000? I need to tell the server about some task duration, so I want it to be just 01:02:01 as a duration. But the sent date is local and the server understands it as 03:02:01! How can I zero the GMT index?

Thanks

Upvotes: 2

Views: 9862

Answers (2)

void
void

Reputation: 36703

function convertToGmt(pdate)
{
var newDate = new Date(pdate);
    return (newDate.getUTCHours()<10?"0"+newDate.getUTCHours():newDate.getUTCHours())+":"+(newDate.getUTCMinutes()<10?"0"+newDate.getUTCMinutes():newDate.getUTCMinutes())+":"+(newDate.getUTCSeconds()<10?"0"+newDate.getUTCSeconds():newDate.getUTCSeconds());
}

Now use this function and call it by passing you date.

Notice that getUTCHours() returns correct hour in UTC.

Working Fiddle

Upvotes: 0

jdphenix
jdphenix

Reputation: 15445

Getting the GMT time out of a JavaScript Date object is simple enough -

Date.prototype.toUTCString() The toUTCString() method converts a date to a string, using the UTC time zone.

For example:

var test = new Date('Thu Jan 01 1970 01:02:01 GMT+0200').toUTCString();
console.log(test);

Note that this correctly outputs Wed, 31 Dec 1969 23:02:01 GMT, which although it not what you are looking for, is converting the provided Date to GMT.

To get what you want out of your input, a regular expression is useful. Caveats:

  • assumes duration will never be more than 23 hours, 59 minutes, and 59 seconds. If it is this will break.

var test = 'Thu Jan 01 1970 01:02:01 GMT+0200';
var durationMatcher = /\d\d:\d\d:\d\d/; 
console.log(test.match(durationMatcher)); 

If you can, consider working in some values that works for you with one number - number of milliseconds for example.

Upvotes: 2

Related Questions