我有脚本需要以这种格式08/25/2017 1:54 PM
我为日期编写代码
这是
$(document).ready(function() {
var dateNow = new Date();
var dd = dateNow.getDate();
var mm = dateNow.getMonth()+1; //January is 0!
var yyyy = dateNow.getFullYear();
if(dd<10) {
dd = '0' + dd;
}
if(mm<10) {
mm = '0' + mm;
}
dateNow = mm + '/' + dd + '/' + yyyy;
alert(dateNow);
});
但我怎样才能以正确的格式获得时间?
答案 0 :(得分:1)
您可以直接使用:
dateNow.getHours()
dateNow.getMinutes()
答案 1 :(得分:0)
此代码应该适合您。
它以所需格式 08/25/2017 1:54 PM
格式化日期
var dateNow = new Date();
var dd = dateNow.getDate();
var mm = dateNow.getMonth()+1; //January is 0!
var yyyy = dateNow.getFullYear();
if(dd<10) {
dd = '0' + dd;
}
if(mm<10) {
mm = '0' + mm;
}
var h = dateNow.getHours(), m = dateNow.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
dateNow = mm + '/' + dd + '/' + yyyy+ ' ' + _time;
alert(dateNow);
答案 2 :(得分:0)
使用此代码:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var str = (date.getMonth() + 1) + "/" +date.getDate() + "/" + date.getFullYear()+ " " + strTime;
console.log(str);