我正在使用 HTML5 元素 datetime-local。我需要两种格式的日期。一个作为日期对象,另一个作为字符串。我将把日期对象存储在数据库中,并使用该字符串来设置日期时间本地表单输入。
我需要将此字符串转换为日期对象:
“2014-06-22T16:01”
我似乎无法获得正确的时间。这就是我得到的。时间不正确。
2014 年 6 月 22 日星期日 09:01:00 GMT-0700(太平洋夏令时)
这就是我格式化日期的方式:
function formatTime(_date) {
var _this = this,
date = (_date) ? _date : new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
seconds = date.getSeconds(),
function addZero(num) {
return num > 9 ? num : '0' + num;
}
minute = addZero(minute);
seconds = addZero(seconds);
hour = addZero(hour);
day = addZero(day);
month = addZero(month);
return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
};
最佳答案
如果您尝试获取 ISO 8601 日期字符串,可以尝试 Date.prototype.toISOString 。但是,它始终使用 UTC。如果您想包含本地时区,请使用如下内容:
/* Return a string in ISO 8601 format with current timezone offset
** e.g. 2014-10-02T23:31:03+0800
** d is a Date object, or defaults to current Date if not supplied.
*/
function toLocalISOString(d) {
// Default to now if no date provided
d = d || new Date();
// Pad to two digits with leading zeros
function pad(n){
return (n<10?'0':'') + n;
}
// Pad to three digits with leading zeros
function padd(n){
return (n<100? '0' : '') + pad(n);
}
// Convert offset in mintues to +/-HHMM
// Note change of sign
// e.g. -600 => +1000, +330 => -0530
function minsToHHMM(n){
var sign = n<0? '-' : '+';
n = Math.abs(n);
var hh = pad(n/60 |0);
var mm = pad(n%60);
return sign + hh + mm;
}
var offset = minsToHHMM(d.getTimezoneOffset() * -1);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
'.' + padd(d.getMilliseconds()) + offset;
}
console.log(toLocalISOString(new Date())); // 2014-06-23T07:58:04.773+0800
编辑
上面可能遗漏了你的问题,这似乎是;
I need to convert this string to a date object: "2014-06-22T16:01"
大概您想将其视为本地时间字符串。 ECMA-262 规定,没有时区的类似 ISO 的字符串将被视为 UTC,而这正是您的主机正在做的事情。因此,您需要一个函数来从字符串创建本地 Date 对象:
function parseYMDHM(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]||0, b[6]||0);
}
console.log(parseYMDHM('2014-06-22T16:01')); // Sun Jun 22 16:01:00 UTC+0800 2014
关于javascript - 从日期时间本地元素转换为日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24356638/