3

我的日期格式为:
2010-11-30T08:32:22+0000
2010-11-27T20:59:17+0000
来自提要,以字符串格式转换为 javascript,现在我想将其转换为 Date 对象。我怎样才能在javascript中做到这一点?

4

8 回答 8

6

此代码适用于 IE/Firefox/Chrome:

new Date("2010-11-30T08:32:22+0000".replace(/-/g,'/').replace(/T/,' ').replace(/\+/,' +'))

它更改2010-11-30T08:32:22+00002010/11/30 08:32:22 +0000然后从固定字符串创建 Date 对象。

我不确定你是否应该使用它,它看起来真的很脏。

于 2010-12-15T14:32:12.303 回答
4

也许这是一个矫枉过正,但试试Datejs

于 2010-12-15T14:24:45.540 回答
4

这个配方不考虑时区。您需要对其进行更多修改才能使其与 TZ 一起使用。如果您确定时区始终为+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中学到的食谱的稍微冗长的版本

于 2010-12-15T14:45:22.080 回答
3

新浏览器版本支持 new Date("2010-11-30T08:32:22+0000") (Chrome, FF4, IE9),但旧浏览器不支持。

如果时区没有意义(在它始终为零(您的情况)或省略的情况下),您可以使用这个:

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")
于 2011-06-01T08:30:57.540 回答
2
var someDate = new Date("2010-11-30T08:32:22+0000");

我不认为它可以更简单。

于 2010-12-15T14:18:28.043 回答
1

非常简单 :

var Date = new Date("2014-02-03T08:32:22+0000");
于 2014-03-02T18:16:50.693 回答
0

这可能是一个选择

> 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)
于 2014-11-13T19:41:28.743 回答
-1

我发现像 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: http://stackoverflow.com/questions/4450837/javascript-string-to-date-php-iso-string-format
// 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>
于 2013-06-13T19:27:35.570 回答