你的位置:首页 > Java教程

[Java教程]js获取当前时间(昨天、今天、明天)


  1. 开发过程中某些前台页面的时间控件我们需要给默认当前时间,jquery可以轻松的帮我们实现,代码如下
     1 //昨天的时间 2 var day1 = new Date(); 3 day1.setTime(day1.getTime()-24*60*60*1000); 4 var s1 = day1.getFullYear()+"-" + (day1.getMonth()+1) + "-" + day1.getDate(); 5 //今天的时间 6 var day2 = new Date(); 7 day2.setTime(day2.getTime()); 8 var s2 = day2.getFullYear()+"-" + (day2.getMonth()+1) + "-" + day2.getDate(); 9 //明天的时间10 var day3 = new Date();11 day3.setTime(day3.getTime()+24*60*60*1000);12 var s3 = day3.getFullYear()+"-" + (day3.getMonth()+1) + "-" + day3.getDate();13 //拼接时间14 function show(){15   var str = "" + s1 + "至" + s2;16   return str;17 }18 //赋值doubleDate19 $('#dateS').val(show());    

     

  2. 下面是具体到时分秒的获取方法
     1 function writeCurrentDate() { 2     var now = new Date(); 3     var year = now.getFullYear(); //得到年份 4     var month = now.getMonth();//得到月份 5     var date = now.getDate();//得到日期 6     var day = now.getDay();//得到周几 7     var hour = now.getHours();//得到小时 8     var minu = now.getMinutes();//得到分钟 9     var sec = now.getSeconds();//得到秒10      var MS = now.getMilliseconds();//获取毫秒11     var week;12     month = month + 1;13     if (month < 10) month = "0" + month;14     if (date < 10) date = "0" + date;15     if (hour < 10) hour = "0" + hour;16     if (minu < 10) minu = "0" + minu;17     if (sec < 10) sec = "0" + sec;18     if (MS < 100)MS = "0" + MS;19     var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");20     week = arr_week[day];21     var time = "";22     time = year + "年" + month + "月" + date + "日" + " " + hour + ":" + minu + ":" + sec + " " + week;23     //当前日期赋值给当前日期输入框中(jQuery easyUI)24     $("#currentDate").html(time);25     //设置得到当前日期的函数的执行间隔时间,每1000毫秒刷新一次。26     var timer = setTimeout("writeCurrentDate()", 1000);27    }