1

让我们从有问题的代码开始:

<div id="debug"></div><br />
<div id="placeholder" class="demo-placeholder"></div>
<script language="javascript" type="text/javascript" src="/doppelog/static/doppelog/js/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="/doppelog/static/doppelog/js/jquery.flot.time.js"></script>
<script type="text/javascript">

    $(function() 
    {
        var alc = 
        {
            label:"ALC", data:
            [
                [1.3765428e+12,2],

                [1.3775796e+12,88],

                [1.377666e+12,109],

                [1.3777524e+12,65],
            ]
        };

        var options = 
        {
            //points: {show:true},
            bars: {show:true, fill: .65, barWidth:0.85*24*60*60*1000}, //leading co-efficient for bar width, other scalars to get to 1 day resolution
            xaxis: 
            {
                mode: "time",
                timeformat: "%Y-%m-%d",
                autoscaleMargin: null
            },
            grid: {hoverable:true}

        };

        function showTooltip(x, y, contents) {
            $("<div id='tooltip'>" + contents + "</div>").css({
                position: "absolute",
                display: "none",
                top: y + 5,
                left: x + 5,
                border: "1px solid #fdd",
                padding: "2px",
                "background-color": "#fee",
                opacity: 0.80
            }).appendTo("body").fadeIn(200);
        };

        var previousPoint = null;
        $("#placeholder").bind("plothover", function (event, pos, item) 
        {

            if (item) 
            {
                if (previousPoint != item.dataIndex) 
                {

                    previousPoint = item.dataIndex;

                    $("#tooltip").remove();
                    var x = item.datapoint[0],
                    y = item.datapoint[1],
                    d = new Date(x),
                    td = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDay();
                    document.getElementById("debug").innerHTML=x;
                    showTooltip(item.pageX, item.pageY, td + ": " + y);
                }
            } 
            else 
            {
                $("#tooltip").remove();
                previousPoint = null;            
            }
        });

        $.plot("#placeholder", [alc], options);
        //document.getElementById("debug").innerHTML=alc[1];
    });

</script>

http://jsfiddle.net/XBCvq/

x 轴上的日期标签是正确的。鼠标悬停时,x 的值显示在顶部的 div 中。当您将其作为“new Date(x)”复制到 Javascript 控制台时,会生成正确的日期。

当您将鼠标悬停在条上时,会出现一个相差一个多月的日期。为什么会这样,我该如何解决?

4

1 回答 1

3

大部分差异是由于月份(由 getMonth 返回)从零开始,其余是因为您没有考虑 UTC 偏移量。

重用 Flot 自己的 formatDate 函数要容易得多,如下所示:

var DATE_FORMAT = "%Y-%m-%d";  // Use this in your plot options as well
...
showTooltip(item.pageX, item.pageY, $.plot.formatDate(d, DATE_FORMAT) + ":" + y);
于 2013-08-31T04:16:08.720 回答