Chrome的日期/时间格式问题

时间:2012-10-08 15:01:21

标签: javascript jquery google-chrome handlebars.js

我在JSON中得到如下的日期/时间值:

"ChangedDate":"\/Date(1349469145000)\/"

在FF和IE中,我使用下面的帮助函数以12小时格式(10/5/2012 - 3:32:25 PM)获得上述日期:

Handlebars.registerHelper('FormatDate', function (date) {
            if (date == null)
                return "";
            else {
                var value = new Date(parseInt(date.substr(6)));
                return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();
            }
        });

然而,在Chrome中,我仍然可以获得24小时格式(10/5/2012 - 15:32:25)。

如何在Chrome中以12小时格式获取日期/时间值?

1 个答案:

答案 0 :(得分:3)

  

当意图向用户显示时使用toLocaleTimeString   使用用户选择的区域格式格式化的字符串。是   意识到这种方法由于其性质而表现不同   取决于操作系统和用户的设置。

您最好更改此行:

return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();

为:

return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + (value.getHours() > 12 ? value.getHours() - 12 : value.getHours()) + ":" + value.getMinutes() + ":" + value.getSeconds();

我们检查小时是否为> 12,如果是,我们从该数字中减去12。

(value.getHours() > 12 ? value.getHours() - 12 : value.getHours())

因此,您的示例15:32:25将是15 - 12 = 33:32:25

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getSeconds

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMinutes

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getHours

修改

//set up example
var date = new Date("10/5/2012");
date.setHours(15,32,25,00);

//Get data from date
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();

var hours = date.getHours();
var amOrPm = "AM";
if(date.getHours() > 12){
    hours = date.getHours() - 12;
    amOrPm = "PM";
}

var minutes = date.getMinutes();
if(minutes  < 10)
    minutes = "0" + minutes;

var seconds = date.getSeconds();
if(seconds < 10)
    seconds = "0" + seconds;

var dateString = month + "/" + day + "/" + year + " - " + hours + ":" + minutes + ":" + seconds;

console.log(dateString);

我让这个例子比需要的更详细,但它有助于向您展示正在发生的事情。希望它有所帮助。

<强> EXAMPLE

简而言之,这看起来像是:

//Get data from date
var dateString = (date.getMonth()+1) + "/" + date.getDate() + "/" +  date.getFullYear() + " - " + (date.getHours() > 12 ? date.getHours() - 12 : date.getHours())+ ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()) + " " + (date.getHours() > 12 ? "PM" : "AM");

<强> EXAMPLE