-4

我想在 javascript 中使用日期函数来获取日期为 9 月 8 日星期日上午 11:46

下面是我正在使用的代码-: var currentTime = new Date()

var dd1 = currentTime.getDate();
var mm1 = currentTime.getMonth()+1; // January is 0!
var yyyy1 = currentTime.getFullYear();

if(dd1 < 10)
{
    dd1 = '0'+ dd1;
}
if(mm1 < 10)
{
    mm1 = '0' + mm1;
}
var date = dd1 + '/' + mm1 + '/' + yyyy1;

但这给出了 -: 08/09/2013 而我想得到它 -: 9 月 8 日星期日上午 11:46

4

4 回答 4

2

以下示例代码会有所帮助:

<!DOCTYPE HTML>
<html>
<body>
<script>

    var current_date = new Date ( );
    var month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var day_names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    var hours = current_date.getHours();
    var minutes = current_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;

    // Display date in required format
    var formatted_date = day_names[current_date.getDay()] + ", " + month_names[current_date.getMonth()] + " " + current_date.getDate() + " at " + " " + hours + ":" + minutes +  ampm ;
    console.log( formatted_date );

</script>

</body>
</html>

资源:

在 javascript 中处理日期格式

以 12 小时 AM/PM 格式显示 javascript 日期时间

于 2013-09-08T06:55:12.960 回答
1

尝试,

var date = new Date( dd1 + '/' + mm1 + '/' + yyyy1);

反而

 var date = dd1 + '/' + mm1 + '/' + yyyy1;

有点乱

var date = new Date  ( dd1 + '/' + mm1 + '/' + yyyy1);
var name = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][date.getDay()];
var monthName = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ][date.getMonth()];
alert (name + " , "  + monthName + " " + date.getDate()+ " at " + "  your time as you like");
于 2013-09-08T06:42:58.330 回答
0

你需要使用一个好的 JavaScript 日期格式库。试试moment.js 你必须阅读他们的格式化文档来弄清楚如何做你需要的——但你可以做到

于 2013-09-08T06:32:24.197 回答
0

也许toDateString功能会有所帮助

var objDate = new Date();
var strDate = objDate.toDateString();
var intHrs = objDate.getHours();
var intMin = objDate.getMinutes();

alert(strDate + ' ' + intHrs + ' : ' + intMins); 

来自 MDN 的 Date 对象的完整参考可在此处获得

于 2013-09-08T06:44:51.910 回答