在javascript中从数组转换日期

时间:2014-09-26 16:37:49

标签: javascript date

我无法弄清楚如何获取日期戳并将其转换为可读日期。我尝试了不同的方法,但我似乎错过了一些东西。我能够获取数组,循环遍历值并抓住我需要的东西,我似乎无法正确转换时间戳(实际上完全正确)。

这是我的完整代码,附有几个注释:

<script>
        var ctx = $("#ertChart").get(0).getContext("2d");
        var myNewChart = new Chart(ctx);

        var ert = @Html.Raw(Json.Encode(Model));  // contains [{""H":"E","consumption":0.46,"readingdatetime":"\/Date(1410678000000)\/"}]

        var ertLabel = []; 
        var ertValue = [];

        for (var i in ert) {
            ertLabel.push(ert[i].formatdate('yy-mm-dd', readingdatetime));  // << this is where I've been playing with the date formatting in different ways
            ertValue.push(ert[i].consumption);
        }

        var ertLabelString = ertLabel.join(",");
        var ertValueString = ertValue.join(",");
        blah
        var data = {
            labels: [ertLabelString],
            datasets: [
                {
                    label: "My First dataset",
                    fillColor: "rgba(220,220,220,0.2)",
                    strokeColor: "rgba(220,220,220,1)",
                    pointColor: "rgba(220,220,220,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: [ertValueString]
                }
            ]
        }
        new Chart(ctx).Line(data);
    </script>

我要做的是将readdatetime转换为

中的可读日期

mm-dd-yyy HH:MM格式,如果H = E

HH:MM如果H = I

有人能指出我正确的方向吗?

以下是修改过的代码爆炸的地方:

var ert = @Html.Raw(Json.Encode(Model));

        var ertLabel = []; 
        var ertValue = [];

        for (var i in ert) {
            var dateString = moment(ert[i].readingdatetime).format("MM-DD-YYYY HH:mm");
            ertValue.push(ert[i].consumption);
        }

        var ertLabelString = dateString.join(",");  // << Exception property or method not valid 'Join'
        var ertValueString = ertValue.join(",");

2 个答案:

答案 0 :(得分:0)

那样的东西?

http://jsfiddle.net/OxyDesign/vs2e618L/

JS

var date = new Date(1410678000000),
    month = date.getMonth()+1, //mm
    day = date.getDate(), //dd
    year = date.getFullYear(), //yyyy
    hours = date.getHours(), //HH
    minutes = date.getMinutes(), //MM
    dateString;

if(month <= 9) month = '0'+month;
if(day <= 9) day = '0'+day;
if(hours <= 9) hours = '0'+hours;
if(minutes <= 9) minutes = '0'+minutes;

dateString = month+'-'+day+'-'+year+' '+hours+':'+minutes;

console.log(dateString);

答案 1 :(得分:0)

您会发现JavaScript中的格式化日期并非易事。考虑使用一个库,例如moment.js,这会让事情变得更容易,并涵盖您可能没有想过的边缘情况。

moment(readingdatetime).format("MM-DD-YYYY HH:mm")