문제

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. How can I do it in javascript?

도움이 되었습니까?

해결책

Perhaps it is an overkill, but try Datejs

다른 팁

This code works in 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.

I'm not sure if you should use this, it seems really dirty.

This recipe doesn't take care of TimeZone. You need to hack it a little more to get it working with TZs. If you are sure that the time-zone is always +0000, this code will work:

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

New browsers version support new Date("2010-11-30T08:32:22+0000") (Chrome, FF4, IE9), but old browsers doesn't.

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

I don't think it could be any simpler.

Very simple :

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

Here is working example you can save as .html file and test on your computer:

<!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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top