分享一些上课时的笔记给大家
运行效果:
实现代码:
<script type="text/javascript">
//日期Date对象方法,必须先实例化再使用,实例化可以传参数 参数为时间戳 或 文本时间
//实例化Date方法给now对象
// var now = new Date('2015-06-05');
// //获取时间戳
// console.log(now.getTime());
// console.log(now.valueOf());
// var nowTime;
// nowTime = now.getFullYear() + '-' + now.getMonth() + '-' + now.getDate();
// console.log(nowTime);
//封装时间格式的string输出函数
function GetTime(datestr) {
//三元判断:变量 = 表达式 ? 真 输出的值 : 假 输出的值;
datestr = datestr == undefined ? Date.now() : datestr;
var now = new Date(datestr);
var year = now.getFullYear();
var month = now.getMonth();
month += 1;
var date = now.getDate();
var hours = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
month = month < 10 ? '0' + month : month;
date = date < 10 ? '0' + date : date;
min = min < 10 ? '0' + min : min;
sec = sec < 10 ? '0' + sec : sec;
var nowTime = year + '-' + month + '-' + date + ' ' + hours + ':' + min + ':' + sec + '';
return nowTime;
}
console.log(GetTime());
console.log(GetTime('2015-5-5 12:12:12'));
</script>