日期/时间格式问题自Chrome

问题描述:

我得到如下的日期/时间值在JSON:日期/时间格式问题自Chrome

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

在FF和IE浏览器,我得到了12小时格式(2012年10月5日在上述日期 - 下午3点32分25秒),使用下面的辅助函数:

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小时格式(2012年10月5日 - 15时32分25秒)。

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

使用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:2515 - 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

+0

谢谢。但是,那么如何添加am/pm值并以两位数字格式(01代替1分钟)显示值? – dotNetNewbie

+0

我会尽快在这里制作一个js小提示给你看,但它的基本原理与上面相同。你会检查分钟是否小于10,如果是,那么你预先设定一个“0”。 am/pm取决于小时数,所以如果它是'> 12',那就是pm,否则就是。 – Chase

+0

让我知道,如果这就是你要找的,如果不是,我会很乐意帮助你更多。谢谢 – Chase