在我的数据库中,我必须将日期时间设置为带有时区的ISO格式。例如,我有以下输入栏:
17/02/2016 22:00:00 +01:00
我有一个接受日期(在JSON对象中)的Web服务,如下所示:
{
//...
"Start": "2016-02-17T22:00:00+01:00"
//...
}
现在在我的javascript代码中我尝试过:
var today = new Date();
var dateString = today.toISOString();
但是dateString的输出是:
"2016-03-05T12:10:32.537Z"
我怎样才能得到这样的字符串:
"2016-03-05T13:10:32.537+01:00"
由于
答案 0 :(得分:0)
我相信您无法直接从Date
函数获取本地ISO 8601格式。 toISOString()
为您提供UTC / GMT的时间: 2016-03-05T12:10:32.537Z (这是Z到底是什么,它意味着UTC)
这是你自己编写字符串的方法:
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;
}
&#13;
<div id='myDiv'></div>
&#13;
您可以查看http://currentmillis.com/?now获取可为您提供多种格式的Javascript
答案 1 :(得分:0)
如果您想要自定义格式,则需要使用Date对象方法自行格式化日期,例如:
date = new Date();
hour= date.getHours();
min= date.getMinutes();
sec= date.getSeconds();
time= hour+':'+min+':'+sec;
console.log(time)
为方便起见,可将其封装在函数或对象方法中。