0

In my database I must put a date time in ISO format with time zone. For example I have the following entry column:

17/02/2016 22:00:00 +01:00

I have a web service that accept a date (in JSON object) like this:

{
    //...
    "Start": "2016-02-17T22:00:00+01:00"
    //...
}

Now in my javascript code i've tried:

var today = new Date();
var dateString = today.toISOString();

But the output of dateString is:

"2016-03-05T12:10:32.537Z"

How can I get a string like this:

"2016-03-05T13:10:32.537+01:00"

Thanks

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Tom
  • 4,007
  • 24
  • 69
  • 105

2 Answers2

0

I believe you can't obtain a local ISO 8601 format directly from a Date function. toISOString() gives you the time in UTC / GMT: 2016-03-05T12:10:32.537Z (that's what the Z in the end is for, it means UTC)

This is how you can do it by composing the string yourself:

var date = new Date(); // this is your input date

var offsetHours = -date.getTimezoneOffset() / 60;
var offsetMinutesForDisplay = Math.abs(-date.getTimezoneOffset() % 60);
var offsetHoursForDisplay = Math.floor(offsetHours) + (offsetHours < 0 && offsetMinutesForDisplay != 0 ? 1 : 0);
var isoOffset = (offsetHours >= 0 ? ("+" + fillDigit(offsetHoursForDisplay, true)) : fillDigit(offsetHoursForDisplay, true)) + ':' + fillDigit(offsetMinutesForDisplay, true);

document.getElementById('myDiv').innerHTML = date.getFullYear() + '-' + fillDigit(date.getMonth() + 1, true) + '-' + fillDigit(date.getDate(), true) + 'T' + fillDigit(date.getHours(), true) + ':' + fillDigit(date.getMinutes(), true) + ':' + fillDigit(date.getSeconds(), true) + isoOffset;

function fillDigit(value, withDigit) { // we want to display 04:00 instead of 4:00
  if (value >= 0 && value < 10) {
    return (withDigit ? "0" : " ") + value;
  }
  if (value > -10 && value < 0) {
    return '-' + (withDigit ? "0" : " ") + (-value);
  }
  return value;
}
<div id='myDiv'></div>

You can check out http://currentmillis.com/?now for Javascript that will get you multiple formats

Sandman
  • 2,577
  • 2
  • 21
  • 32
0

If you want a custom format you need format the date by yourself using Date object methods like:

date = new Date();
hour= date.getHours();
min= date.getMinutes();
sec= date.getSeconds();

time= hour+':'+min+':'+sec;
console.log(time)

This can be encapsulated in a function or in a object method for convenience.

scaamanho
  • 51
  • 2