Flot工具提示中显示的日期不正确

时间:2013-08-30 20:09:03

标签: javascript date flot

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

<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的值显示在顶部顶部。当您将其作为“新日期(x)”复制到Javascript控制台时,会生成正确的日期。

当您将鼠标悬停在某个条形图上时,会显示超过一个月的日期。为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分: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);