时间的API

getFullYear() 获取当年
getMonth() 获取当月
getDate() 获取当天日期
getDay() 获取星期几(周日0 到 周六6)
getHours() 获取当前小时
getMinutes() 获取当前分钟
getSeconds() 获取当前秒钟
getTime() valueOf() 都是获取当前时间距离1970年1月1号过了的毫秒数
Date.now() 同上

 


还有一些的有关于时间APl的习题

 

 

// 1. 如何自定义四舍五入的方法 要求是能根据任意小数位四舍五入
// var num = Number(prompt('请输入你要取整的小数:'));
// console.log(num)
// var n = prompt('请输入你要保留的位数');
// console.log(num.toFixed(n));
function one(){
var num = prompt('请输入你要取整的小数:');
var d = prompt('请输入你要保留的位数');
try{
if(isNaN(num) || isNaN(d)){
console.log('请输入正确的数字!')
}else{
num = num*Math.pow(10,d);
num = Math.round(num);
console.log(num/Math.pow(10,d));
}
}catch(e){
console.log(String(e));
}
}

// 2. 算术计算的游戏,随机出十道题,接受用户答题,答对一题得10分,错一题扣10
// 如果输入的是exit,退出游戏最终给出得分
//
function two(){
var count = 0;
for(var i = 1; i < 11;i++){
var num1 = parseInt(Math.random()*10),num2 = parseInt(Math.random()*10);
var num = prompt(num1 + '+' + num2 + '的值是:');
if(num1 + num2 == num){
count += 10;
}else if (num == 'exit'){
break;
}else{
count -= 10;
}
}console.log('最终得分是:' + count);
}

// 3.计算两个时间之间相差的小时数
function three(){
var first = prompt('请输入第一个时间:');
var firstdate = new Date(first);
var second = prompt('请输入第二个时间:');
var seconddate = new Date(second);
var time = (seconddate - firstdate)/3600000;
console.log('中间相差了' + time + '个小时');
}

// 4当前时间格式化为:xxx年x月x日 星期x am/pm hh:mm:ss
function four(){
var nowdate = new Date();
console.log(nowdate);
var day = nowdate.getDay() == 0?'六':nowdate.getDay() == 1?'一':nowdate.getDay() == 2?'二':nowdate.getDay() == 3?'三':nowdate.getDay() == 4?'四':nowdate.getDay() == 5?'五':'六';
var hours;
if(nowdate.getHours() > 12){
hours = 'pm';
}else{
aours = 'am';
}
var time = nowdate.getFullYear() + '年' + (nowdate.getMonth() + 1) + '月' + nowdate.getDate() + '日 ' + ' 星期' + day +' ' + hours + ' ' + nowdate.getHours() + ':' + nowdate.getMinutes() + ':' + nowdate.getSeconds();
console.log(time)
}

posted @ 2019-08-02 18:16  石舟丿  阅读(308)  评论(0编辑  收藏  举报