偶实现的代码
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>最少的代码实现当前的星期加时间</title>
</head>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<h3 style=" text-align: center; padding-top: 6px;" id="weektime"></h3>
<script type="text/javascript">
$(function() {
weekTime();
});
//最少的代码实现当前的星期加时间,如果时间是个位数的前面补零
function weekTime(){
var now = new Date();
var today = new Array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');
var week = today[now.getDay()];
var hh = now.getHours(), mm = now.getMinutes(), ss = now.getSeconds();
function zerofill(obj) { return obj < 10 ? '0' + obj : obj;}
$('#weektime').text(week+' '+ zerofill(hh) + ':' + zerofill(mm) + ':' + zerofill(ss));
}
</script>
</body>
</html>
结果群友(凌烟)实现更短的代码:
function weekTime(){
var now = new Date();
var week = '星期' + ['日','一','二','三','四','五','六'][now.getDay()];
var hh = now.getHours(), mm = now.getMinutes(), ss = now.getSeconds();
function zerofill(obj) { return obj < 10 ? '0' + obj : obj;}
$('#weektime').text(week+' '+ zerofill(hh) + ':' + zerofill(mm) + ':' + zerofill(ss));
}
结果群友(hi)实现更短的代码:
function weekTime(){
var now = new Date();
//var week = now.toLocaleDateString("zh-cn", {weekday:'long'});
var week = '星期' + '日一二三四五六'.charAt(now.getDay());
var hh = now.getHours(), mm = now.getMinutes(), ss = now.getSeconds();
function zerofill(obj) { return obj < 10 ? '0' + obj : obj;}
$('#weektime').text(week+' '+ zerofill(hh) + ':' + zerofill(mm) + ':' + zerofill(ss));
}
效果图: