我有一个日期格式如下:
它来自于一个源,以字符串格式传递到javascript中,现在我想将其转换为Date对象。在javascript中该如何实现?
2010-11-30T08:32:22+0000
2010-11-27T20:59:17+0000
它来自于一个源,以字符串格式传递到javascript中,现在我想将其转换为Date对象。在javascript中该如何实现?
2010-11-30T08:32:22+0000
2010-11-27T20:59:17+0000
这段代码在IE/Firefox/Chrome中都能正常工作:
new Date("2010-11-30T08:32:22+0000".replace(/-/g,'/').replace(/T/,' ').replace(/\+/,' +'))
它将 2010-11-30T08:32:22+0000
转换为 2010/11/30 08:32:22 +0000
,然后从固定字符串创建 Date 对象。
我不确定你是否应该使用它,因为它看起来很糟糕。
这个示例代码没有处理时区问题。你需要做更多的修改才能让它与时区兼容。如果你确定时区始终为+0000
,则此代码将适用:
var s = "2010-11-30T08:32:22+0000";
// Replace non-digit characters with a space
s = s.replace(/\D/g," ");
// Split the string on space
var date_parts = s.split(" ");
// subtract 1 from month to use in Date constructor
var yyyy = date_parts[0],
mm = date_parts[1] - 1,
dd = date_parts[2],
hh = date_parts[3],
mi = date_parts[4],
ss = date_parts[5];
// Now, the date_parts has year, month, date and so on
var dt = new Date(yyyy, mm, dd, hh, mi, ss);
这是我从JavaScript Cookbook学到的一份略显冗长的食谱。
Date.fromISOString = (function(){
function fastDateParse(y, m, d, h, i, s, ms){
return new Date(y, m - 1, d, h || 0, i || 0, s || 0, ms || 0);
}
// result function
return function(isoDateString){
return fastDateParse.apply(null, isoDateString.split(/\D/));
}
})();
Date.fromISOString = (function(){
var tzoffset = (new Date).getTimezoneOffset();
function fastDateParse(y, m, d, h, i, s, ms){ // this -> tz
return new Date(y, m - 1, d, h || 0, +(i || 0) - this, s || 0, ms || 0);
}
// result function
return function(isoDateString){
var tz = isoDateString.substr(10).match(/([\-\+])(\d{1,2}):?(\d{1,2})?/) || 0;
if (tz)
tz = tzoffset + (tz[1] == '-' ? -1 : 1) * (tz[3] != null ? +tz[2] * 60 + (+tz[3]) : +tz[2]);
return fastDateParse.apply(tz || 0, isoDateString.split(/\D/));
}
})();
日期的正确形式:
Date.fromISOString('2011-06-01');
Date.fromISOString('2011-06-01T00:00:00');
Date.fromISOString('2011-06-01T00:00:00Z');
Date.fromISOString('2011-06-01T00:00:00+30');
Date.fromISOString('2011-06-01T00:00:00-30');
Date.fromISOString('2011-06-01T00:00:00+0530');
Date.fromISOString('2011-06-01T00:00:00-0530');
Date.fromISOString('2011-06-01T00:00:00+05:30');
Date.fromISOString('2011-06-01T00:00:00-05:30');
// Your example valid as well.
Date.fromISOString("2010-11-30T08:32:22+0000")
Very simple :
var Date = new Date("2014-02-03T08:32:22+0000");
这可能是一个选项
> s = '2010-11-30T08:32:22+0000'.split(/\D/);
> new Date(Date.UTC(s[0], --s[1]||'', s[2]||'', s[3]||'', s[4]||'', s[5]||'', s[6]||''))
Tue Nov 30 2010 06:32:22 GMT-0200 (BRST)
我发现像 Date.fromISOString('2011-06-01T00:00:00Z') 这样的情况会创建一个带有时区偏移的日期,因此只有在您的计算机处于 GMT 时才能正常工作。这是我所做的更改来修复它。
为了从任何给定的 ISO 字符串中获取正确的日期,即使给定的条目是 GMT,您也需要调整本地时区。
这里是一个可保存为 .html 文件并在您的计算机上测试的工作示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
<head>
<title>ISO Dates String to Date</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="JavaScript">
// Modified from: https://dev59.com/n1LTa4cB1Zd3GeqPcq5m
// Thank you Roman Dvornov
Date.fromISOString = (function(){
var tzoffset = (new Date).getTimezoneOffset();
function fastDateParse(y, m, d, h, i, s, ms){ // this -> tz
return new Date(y, m - 1, d, h || 0, +(i || 0) - this, s || 0, ms || 0);
}
// result function
return function(isoDateString){
var tz = isoDateString.substr(10).match(/([\-\+])(\d{1,2}):?(\d{1,2})?/) || 0;
if (tz) {
tz = tzoffset + (tz[1] == '-' ? -1 : 1) * (tz[3] != null ? +tz[2] * 60 + (+tz[3]) : +tz[2]);
} else {
tz = tzoffset;
}
return fastDateParse.apply(tz || 0, isoDateString.split(/\D/));
}
})();
function checkDate() {
showDateIso($('#IsoStringInput').val());
}
function dates() {
showDateIso('2011-06-01');
showDateIso('2011-06-01T00:00:00');
showDateIso('2011-06-01T00:00:00Z');
showDateIso('2011-06-01T00:00:00+30');
showDateIso('2011-06-01T00:00:00-30');
showDateIso('2011-06-01T00:00:00+0530');
showDateIso('2011-06-01T00:00:00-0530');
showDateIso('2011-06-01T00:00:00+05:30');
showDateIso('2011-06-01T00:00:00-05:30');
}
function showDateIso(isoString) {
var $tr = $('<tr/>').prependTo($('#DatesTable').find('tbody'));
$('<td/>').appendTo($tr).text(isoString);
var isoDate = Date.fromISOString(isoString);
$('<td/>').appendTo($tr).text(isoDate);
var now = new Date();
$('<td/>').appendTo($tr).text(now);
$('<td/>').appendTo($tr).text(showTimeDiff(now.getTime() - isoDate.getTime()));
$tr.fadeOut(100).fadeIn(1400);
}
var ONE_YEAR_MS = 31536000000;
var ONE_WEEK_MS = 604800000;
var ONE_DAY_MS = 86400000;
var ONE_HOUR_MS = 3600000;
var ONE_MINUTE_MS = 60000;
function showTimeDiff(timeMs) {
var result = '';
if (typeof(timeMs) !== 'undefined') {
var years = 0;
while (timeMs >= ONE_YEAR_MS) {
years = years + 1;
timeMs = timeMs - ONE_YEAR_MS;
}
if (years > 0) {
result = result + years + ((weeks === 1) ? ' year ' : ' years ');
}
var weeks = 0;
while (timeMs >= ONE_WEEK_MS) {
weeks = weeks + 1;
timeMs = timeMs - ONE_WEEK_MS;
}
if (weeks > 0) {
result = result + weeks + ((weeks === 1) ? ' week ' : ' weeks ');
}
var days = 0;
while (timeMs >= ONE_DAY_MS) {
days = days + 1;
timeMs = timeMs - ONE_DAY_MS;
}
if (days > 0) {
result = result + days + ((days === 1) ? ' day ' : ' days ');
}
var hours = 0;
while (timeMs >= ONE_HOUR_MS) {
hours = hours + 1;
timeMs = timeMs - ONE_HOUR_MS;
}
var minutes = 0;
while (timeMs >= ONE_MINUTE_MS) {
minutes = minutes + 1;
timeMs = timeMs - ONE_MINUTE_MS;
}
// Break down to seconds
var seconds = parseInt(timeMs / 1000, 10);
if (hours > 0) {
result = result + hours + ':' + pad(minutes, 2) + ':' + pad(seconds, 2);
} else if (minutes > 0) {
result = result + minutes + ':' + pad(seconds, 2);
} else if (seconds > 0) {
result = result + seconds + ' sec';
}
}
return result;
}
function pad(number, len) {
var result = '';
if (!isNaN(number)) {
result = '' + number;
while (result.length < len) {
result = '0' + result;
}
}
return result;
}
</script>
</head>
<body>
<div>
<label>ISO String:</label>
<input id="IsoStringInput" type="text" value="" style="width: 300px;"/>
</div>
<button type="button" onclick="checkDate();">Check Entered Date</button>
<button type="button" onclick="dates();">ISO for June 01, 2011</button>
<table id="DatesTable">
<thead>
<th>ISO String</th>
<th>Date Printed <span style="color: #888888;">(Local Timezone)</span></th>
<th>Now</th>
<th>Now - ISO <span style="color: #888888;">(minutes)</span></th>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>