简体   繁体   English

javascript - 迄今为止的字符串 - php iso字符串格式

[英]javascript - string to date - php iso string format

I have a date in format of: 我的格式为:
2010-11-30T08:32:22+0000
2010-11-27T20:59:17+0000
coming from a feed, in string format to javascript, now I want to convert it to a Date object. 来自feed,以字符串格式转换为javascript,现在我想将其转换为Date对象。 How can I do it in javascript? 我怎么能用javascript做到这一点?

This code works in IE/Firefox/Chrome: 此代码适用于IE / Firefox / Chrome:

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

It changes 2010-11-30T08:32:22+0000 to 2010/11/30 08:32:22 +0000 and then creates the Date object from the fixed string. 它将2010-11-30T08:32:22+0000更改为2010/11/30 08:32:22 +0000 ,然后从固定字符串创建Date对象。

I'm not sure if you should use this, it seems really dirty. 我不确定你是否应该使用它,它看起来真的很脏。

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

This recipe doesn't take care of TimeZone. 这个食谱不关心TimeZone。 You need to hack it a little more to get it working with TZs. 你需要再多一点才能让它与TZ一起工作。 If you are sure that the time-zone is always +0000 , this code will work: 如果您确定时区始终为+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);

This is a slightly verbose version of a recipe I have learned from JavaScript Cookbook 这是我从JavaScript Cookbook中学到的一个稍微详细的配方版本

New browsers version support new Date("2010-11-30T08:32:22+0000") (Chrome, FF4, IE9), but old browsers doesn't. 新浏览器版本支持新日期(“2010-11-30T08:32:22 + 0000”)(Chrome,FF4,IE9),但旧浏览器不支持。

If timezone doesn't make sence (in cases when it always zero (your case) or omit), you can use this: 如果时区没有出现(如果时区始终为零(您的情况)或省略),您可以使用:

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/));
  }
})();

If you need parse with timezone use this: 如果需要使用时区解析,请使用:

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/));
  }
})();

Correct forms of date: 正确的日期形式:

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")
var someDate = new Date("2010-11-30T08:32:22+0000");

我认为它不会更简单。

很简单 :

var Date = new Date("2014-02-03T08:32:22+0000");

This may be an option 这可能是一种选择

> 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)

I found case like Date.fromISOString('2011-06-01T00:00:00Z') creates date that is offset by timezone, so this only works correctly if your computer is in GMT. 我发现像Date.fromISOString('2011-06-01T00:00:00Z')这样的情况会创建一个由时区偏移的日期,所以这只有在你的计算机处于GMT状态时才能正常工作。 Here is change I made to fix that. 这是我为解决这个问题所做的改变。

To get correct date from any given ISO string, you want to adjust local timezone even if the given entry is GMT. 要从任何给定的ISO字符串中获取正确的日期,即使给定的条目是GMT,也要调整本地时区。

Here is working example you can save as .html file and test on your computer: 这是一个工作示例,您可以将其保存为.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM