3

I need to convert a hard coded date into a standard GMT format.How can I do this? The date I have is in the following format: var myDate = 'dd|mm|yyyy'; There is no time or day description in the date.Just the 'dd|mm|yyyy' string. Is there a way I can convert it into GMT?

Thanks in advance.

Chiranjit
  • 53
  • 1
  • 8
  • You can take a look at this question for inspiration: http://stackoverflow.com/q/7151543/1669279 – Tibos Feb 20 '14 at 13:34

2 Answers2

2
a = '22/02/2014'.split('/')
d = new Date(a[2],parseInt(a[1], 10) - 1,a[0])
//Sat Feb 22 2014 00:00:00 GMT+0530 (India Standard Time)

Now you have a javascript date object in d

utc = d.getUTCDate() + "/" + (d.getUTCMonth() + 1 ) + "/" + d.getUTCFullYear();
//"21/2/2014" for an accurate conversion to UTC time of day is a must.

If you are in say India, the Javascript Date object will have timeZoneOffset 330. So its not possible to keep a javascript Date object with timezone GMT unless your system time is GMT.

So if you want a Date object for calculation, you can create one with localTimezone and simply suppose it is GMT

pseudoGMT = new Date( Date.parse(d) + d.getTimezoneOffset() * 60 * 1000);
//Fri Feb 21 2014 18:30:00 GMT+0530 (India Standard Time)

If you can explain your high level requirement we might be able to help with some alternate solutions.

sabithpocker
  • 15,274
  • 1
  • 42
  • 75
  • Thanks for your help. But can I get a standard date object on which I can apply various methods of date available in javascript? – Chiranjit Feb 20 '14 at 14:41
  • @Chiranjit that is tricky. If you make a Date object it will have your local timezoneOffset, you cannot keep a Date object with GMT offset unless you are there. That being said I'll update with a psuedo solution. – sabithpocker Feb 20 '14 at 17:07
  • Actually I am getting the date from a service just as a string in the format 'mm/dd/yyyy' and I need to navigate through week by week starting from that date.Let's say the day is '02/16/2014' then my current week will be '02/16/2014' t0 '02/22/2014'.If I click next button it will take me to the next week and so on. So in above example you explained it in the 'dd/mm/yyyy' format, how can we do the same with the 'mm/dd/yyyy' format? – Chiranjit Feb 21 '14 at 11:32
1

Use regex matching to extract the data you need:

var myDate = "21|01|2014";
var data = myDate.match(/(\d{2})\|(\d{2})\|(\d{4})/);
var date = new Date(data[3], data[2] - 1, data[1]);

Note that the month is 0-indexed, so january = 0

More on regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Bart
  • 26,399
  • 1
  • 23
  • 24