2

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

Muayad Salah
  • 701
  • 1
  • 8
  • 19
  • You can use UTC to avoid timezone difference, but I will prefer to send and operate a number of seconds – Max Zuber Feb 16 '15 at 08:02
  • Maybe this can help you. [http://stackoverflow.com/questions/8945029/converting-date-to-gmt-0][1] [1]: http://stackoverflow.com/questions/8945029/converting-date-to-gmt-0 – Dade Feb 16 '15 at 08:02

2 Answers2

2

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.

jdphenix
  • 15,022
  • 3
  • 41
  • 74
0
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

void
  • 36,090
  • 8
  • 62
  • 107