如何Monday, February 18, 2013 10:52
使用 Javascript 日期函数在我的 HTML 页面中显示日期时间格式?
更新:
我在尝试
var d=new Date();
var n=d.toString();
document.write(n);
但我希望时间应该自动更新而不是页面刷新。我需要使用 AJAX 吗?
如何Monday, February 18, 2013 10:52
使用 Javascript 日期函数在我的 HTML 页面中显示日期时间格式?
更新:
我在尝试
var d=new Date();
var n=d.toString();
document.write(n);
但我希望时间应该自动更新而不是页面刷新。我需要使用 AJAX 吗?
我正在使用以下代码以我想要的格式显示日期
<script type="text/javascript">
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
document.write(days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +": " + minutes);
</script>
试试这个:- http://jsfiddle.net/2Fj7m/
日期和时间会自动更新。
HTML:-
<body onload="startTime()">
<div id="txt" ></div>
</body>
JS:-
var months = new Array('January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October', 'November', 'December');
var days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var weekday = days[today.getDay()];
var month = months[today.getMonth()];
var year = today.getFullYear();
day = today.getUTCDate();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =weekday + ", " +month +" "+ day+", " + year+ " "+ h + ":" + m;
t = setTimeout(function () {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
如果你加载了 jQuery,你可以这样做:
HTML:
<div id='date'/>
JavaScript:
$('#date').append(Date().toString())
您应该使用 javascript 调试器作为 firebug 或 chrome 的调试器,它将显示所有可用的本机 javascript 函数。
您可以使用
var myDate = new Date();
myDate.toLocaleFormat();
或者
myDate.toLocaleString();
两者都会给
Monday, 18 February, 2013 10:57:46 AM
这与您在问题中提到的格式接近。
.Date()
您可以使用javascript 中的函数创建此格式
$(document).ready(function() {
var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var dayNames = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var today = new Date();
var cDay = today.getDay();
var cDate = today.getDate();
var cMonth = today.getMonth();
var cYear = today.getFullYear();
var cHour = today.getHours();
var cMin = today.getMinutes();
var cSec = today.getSeconds();
alert(dayNames[cDay]+ "," + " "+ monthNames[cMonth] + " " +cDate + "," +cYear + " " +cHour+ ":" + cMin+ ":" +cSec );
});