开发者

Javascript's Date function always returns current time with differend Json strings as input

开发者 https://www.devze.com 2023-03-29 14:08 出处:网络
I\'ve got a AJAX call that returns a JSON string containing several different DateTimes. If I don\'t convert them, I get strings like /Date(1224043200000-0600)/. If I convert them using the Date funct

I've got a AJAX call that returns a JSON string containing several different DateTimes. If I don't convert them, I get strings like /Date(1224043200000-0600)/. If I convert them using the Date function in JavaScript, it returns the current time. I've read a post about this, but it doesn't answer my question. Here's a simplified script which can be pasted in a new file which shows my problem. The Raw Span should show the original string and the Converted Span should show the converted object.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr">
    <body>
        <span id="raw">Raw</span><br />
        <span id="converted">Converted</span>

        <script type="text/javascript">
            var datum = "/Date(1224043200000-开发者_运维百科0600)/";

            function formatDate(value) {
                return Date(value);
            }

            var RAW = document.getElementById("raw");
            var CONVERTED = document.getElementById("converted");

            RAW.innerHTML = datum;
            CONVERTED.innerHTML = formatDate(datum);
        </script>
    </body>
</html>

The result of this code is as follows:

/Date(1224043200000-0600)/
 Mon Aug 22 10:35:21 UTC+0200 2011 

Can someone tell my what I should do to show the right DateTime in the object? The grid which contains all my dates, shows the current time in every cell, although JSON returns different strings all the time.


There's a bug in your code, you are returning a call to the Date object, which gets the current date as a string. You should do a return new Date(value); to get a new object.

Also add this:

var date = new Date(parseInt(datum.substr(6)));
CONVERTED.innerHTML = formatDate(date);

See a test here http://jsfiddle.net/uwSCN/ .

0

精彩评论

暂无评论...
验证码 换一张
取 消