-1

I am working on date conversion. I am converting this 2017-08-17 13:00:00 format of date to 2017-08-17T13:00:00Z

working example:

var from_date;
var sdate = new Date( '2017-08-17 13:00:00' );
var utcSDate = sdate.toISOString();
from_date = utcSDate.replace('.000', '');
console.log(from_date);

But this code change time from 13:00:00 to 08:00:00. Why this is happeining. Any idea ? OR someone give me an idea to convert date from my input to desired output as stated above.

Noob Player
  • 279
  • 6
  • 25

3 Answers3

0

I suggest just to replace the missing parts, without using Date object, where you input the local time and get the zulu time.

var date = '2017-08-17 13:00:00',
    iso = date.replace(/(.{10}) (.{8})/, '$1T$2.000Z');

console.log(date);
console.log(iso);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can substract the offset from your date object:

var d = new Date();
var offsetInMinutes = d.getTimezoneOffset();
d.setMinutes(d.getMinutes() - offsetInMinutes);
d.toISOString()
kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25
0

But this code change time from 13:00:00 to 08:00:00. Why this is happeining. Any idea ? OR someone give me an idea to convert date from my input to desired output as stated above.

The string "2017-08-17 13:00:00" is not a format supported by ECMA-262, so however it is parsed is entirely implementation dependent, see Why does Date.parse give incorrect results? If it is parsed to a Date, it is likely to be treated as ISO 8601 local, i.e. as "2017-08-17T13:00:00". Safari will return an invalid date, Firefox will parse it as local.

So always avoid the built-in parser.

If you just want to reformat the string, do that as a string:

var s = '2017-08-17 13:00:00';
console.log(s.replace(' ','T') + 'Z');

However, you have just change the date and time to UTC+0000 from whatever timezone it was in originally. If you want to consider the host timezone offset, then you should parse the string to a date manually (a library can help but isn't necessary for a single format), then use toISOString:

// Given a string in ISO 8601 like format, parse as local 
function parseISOLocal(s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1]-1, b[2], (b[3] || 0),
    (b[4] || 0), (b[5] || 0));
}

var s = '2017-08-17 13:00:00';

console.log(parseISOLocal(s).toISOString())
RobG
  • 142,382
  • 31
  • 172
  • 209