gpt4 book ai didi

javascript - 从 datetime-local 元素转换为日期对象

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:37 24 4
gpt4 key购买 nike

我正在使用 HTML5 元素 datetime-local。我需要有两种格式的日期。一个作为日期对象,另一个作为字符串。我打算将日期对象存储在数据库中,我将使用字符串来设置日期时间本地表单输入。

我需要将这个字符串转换为日期对象:
“2014-06-22T16:01”

我似乎无法得到正确的时间。这就是我得到的。时间不对。
2014 年 6 月 22 日星期日 09:01:00 GMT-0700 (PDT)

这是我格式化日期的方式:

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;

};

例子: http://codepen.io/zerostyle/pen/gwpuK/

最佳答案

如果你想获取 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 - 从 datetime-local 元素转换为日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24356638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com