JS/jQuery实现获取时间的方法及常用类完整示例


Posted in jQuery onMarch 07, 2019

本文实例讲述了JS jQuery实现获取时间的方法及常用类。分享给大家供大家参考,具体如下:

效果图

JS/jQuery实现获取时间的方法及常用类完整示例

源码解析

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS获取时间的方法及常用类</title>
  <style type="text/css">
    input{
      color:red;
      min-width: 250px;
    }
    /*设置placeholder的颜色*/
    ::-webkit-input-placeholder { /* WebKit browsers */
      color:  #999;
    }
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
      color:  #999;
    }
    ::-moz-placeholder { /* Mozilla Firefox 19+ */
      color:  #999;
    }
    :-ms-input-placeholder { /* Internet Explorer 10+ */
      color:  #999;
    }
    p{
      width:100%;height:0px;border-top:1px orange dashed;
    }
  </style>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
  <h2>JS获取时间的方法及常用类</h2>
  <h4>获取当前日期+时间</h4>
  <input type="text" name="myDate">
  <hr>
  <h4>使用内置的Date函数获取javascript时间</h4>
  当前年:<input type="text" name="getFullYear">
  <br>
  当前月:<input type="text" name="getMonth">  <font color="green">0-11,0代表一月份</font>
  <br>
  当前日:<input type="text" name="getDate">
  <br>
  当前星期:<input type="text" name="getDay">  <font color="green">0-6,0代表周日</font>
  <br>
  当前时间戳(精确毫秒):<input type="text" name="getTime">  <font color="green">从1970.1.1开始的毫秒数</font>
  <br>
  当前小时:<input type="text" name="getHours">  <font color="green">0-23</font>
  <br>
  当前分钟:<input type="text" name="getMinutes">  <font color="green">0-59</font>
  <br>
  当前秒数:<input type="text" name="getSeconds">  <font color="green">0-59</font>
  <br>
  当前毫秒数:<input type="text" name="getMilliseconds">  <font color="green">0-999</font>
  <br>
  当前日期:<input type="text" name="nowDate">
  <br>
  当前时间:<input type="text" name="nowTime">
  <br>
  当前日期+时间:<input type="text" name="nowDateAddNowTime">
  <br>
  <hr>
  <h4>日期时间脚本库方法列表</h4>
  判断闰年:
  <input type="radio" name="isLeapYears" value="1">闰年
  <input type="radio" name="isLeapYears" value="0">非闰年
  <p></p>
  日期格式化:
  <br/>
  年份(YYYY/yyyy):<input type="text" name="formatYear1">  (YY/yy):<input type="text" name="formatYear2">
  <br/>
  月份(MM):<input type="text" name="formatMonth1">  (M):<input type="text" name="formatMonth2">
  <br/>
  星期(W/w):<input type="text" name="formatWeek">
  <br/>
  日(DD/dd):<input type="text" name="formatDay1">  (D/d):<input type="text" name="formatDay2">
  <br/>
  时(HH/hh):<input type="text" name="formatHour1">  (H/h):<input type="text" name="formatHour2">
  <br/>
  分(mm):<input type="text" name="formatMinute1">  (m):<input type="text" name="formatMinute2">
  <br/>
  秒(SS/S):<input type="text" name="formatSecond1">  (ss/s):<input type="text" name="formatSecond2">
  <br/>
  <p></p>
  日期天数差:日期格式YYYY-MM-dd
  <br>
  起始日期:<input type="text" name="s_date" value="2018-08-01" /> 
  截止日期:<input type="text" name="e_date" value="2018-08-06" /> 
  日期差天数:<input type="text" name="diff_date">
  <p></p>
  日期计算:返回对象数据格式:"2018-08-06T06:29:49.000Z",可以调用对象的方法,比如getFullYear();
  <br>
  当前日期:<input type="text" name="date_now"><br/>
  2秒后的时间:<input type="text" name="second_now"><br/>
  2小时后的时间:<input type="text" name="hour_now"><br/>
  2天后的时间:<input type="text" name="day_now"><br/>
  2周后的时间:<input type="text" name="week_now"><br/>
  一季度后的时间:<input type="text" name="quarter_now"><br/>
  一个月后的时间:<input type="text" name="month_now"><br/>
  一年后的时间:<input type="text" name="year_now"><br/>
  <p></p>
  重载toString方法:"一"=====>"星期一"
  <br>
  <input type="text" name="reset_string">
  <P></P>
  日期合法性校验(年月日):正确格式YYYY-MM-DD 或者 YYYY/MM/DD
  <br>
  输入日期:
  <input type="text" name="checkDate" placeholder="YYYY-MM-DD或YYYY/MM/DD">  
  <input type="button" name="checkInputDate" value="检验" style="width:50px;">
  <p></p>
  日期合法性校验(年月日 时分秒):正确格式YYYY-MM-DD HH:II:SS
  <br>
  输入日期:
  <input type="text" name="checkDate1" placeholder="YYYY-MM-DD HH:II:SS">  
  <input type="button" name="checkInputDate1" value="检验1" style="width:50px;">
  <hr>
  日期分割成数组:
  <input type="text" name="splitDate"> <font color="green">取年份</font>
  <script type="text/javascript">
    $(function(){
      //获取当前日期+时间
      var myDate = new Date();
      var t = myDate.toLocaleString();
      inputToValue('text','myDate',t);
      //============================================================
      //使用内置的Date函数获取javascript时间
      var newDate = new Date();
      var getFullYear = newDate.getFullYear();//当前年
      inputToValue('text','getFullYear',getFullYear);
      var getMonth = newDate.getMonth();//当前月
      inputToValue('text','getMonth',getMonth);
      var getDate = newDate.getDate();//当前日
      inputToValue('text','getDate',getDate);
      var getDay = newDate.getDay();//当前星期
      inputToValue('text','getDay',getDay);
      var getTime = newDate.getTime();//当前时间戳(精确毫秒)
      inputToValue('text','getTime',getTime);
      var getHours = newDate.getHours();//当前小时
      inputToValue('text','getHours',getHours);
      var getMinutes = newDate.getMinutes();//当前分钟
      inputToValue('text','getMinutes',getMinutes);
      var getSeconds = newDate.getSeconds();//当前秒数
      inputToValue('text','getSeconds',getSeconds);
      var getMilliseconds = newDate.getMilliseconds();//当前毫秒数
      inputToValue('text','getMilliseconds',getMilliseconds);
      var nowDate = newDate.toLocaleDateString();//当前日期
      inputToValue('text','nowDate',nowDate);
      var nowTime = newDate.toLocaleTimeString();//当前时间
      inputToValue('text','nowTime',nowTime);
      var nowDateAddNowTime = newDate.toLocaleString();//当前时间
      inputToValue('text','nowDateAddNowTime',nowDateAddNowTime);
      //============================================================
      //检测是否为闰年,方法一
      Date.prototype.isLeapYears = function(){
        return (this.getYear() % 4 == 0) && (this.getYear() % 100 != 0 || this.getYear() % 400 == 0);
      }
      var dd1 = new Date();
      //检测是否为闰年,方法二
      function checkYear(year){
        return (year % 4 == 0 && (year % 100 !=0 || year % 400 !=0));
      }
      if(dd1.isLeapYears()){//checkYear(2018)
        $("input[type='radio'][name='isLeapYears'][value='1']").prop("checked",true);
      }else{
        $("input[type='radio'][name='isLeapYears'][value='0']").prop("checked",true);
      }
      //日期格式化
      Date.prototype.Format = function(formatStr){
        var str = formatStr;
        var Week = ['日','一','二','三','四','五','六'];
        str=str.replace(/yyyy|YYYY/,this.getFullYear());
        str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));
        str=str.replace(/MM/,this.getMonth()>9?this.getMonth().toString():'0' + this.getMonth());
        str=str.replace(/M/g,this.getMonth());
        str=str.replace(/w|W/g,Week[this.getDay()]);
        str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
        str=str.replace(/d|D/g,this.getDate());
        str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
        str=str.replace(/h|H/g,this.getHours());
        str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
        str=str.replace(/m/g,this.getMinutes());
        str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
        str=str.replace(/s|S/g,this.getSeconds());
        return str;
      }
      var dd2 = new Date();
      inputToValue('text','formatYear1',dd2.Format('YYYY'));//YYYY/yyyy
      inputToValue('text','formatYear2',dd2.Format('YY'));//YY/yy
      inputToValue('text','formatMonth1',dd2.Format('MM'));//MM
      inputToValue('text','formatMonth2',dd2.Format('M'));//M
      inputToValue('text','formatWeek',dd2.Format('W'));//W/w
      inputToValue('text','formatDay1',dd2.Format('DD'));//DD/dd
      inputToValue('text','formatDay2',dd2.Format('d'));//dd/d
      inputToValue('text','formatHour1',dd2.Format('HH'));//HH/hh
      inputToValue('text','formatHour2',dd2.Format('h'));//H/h
      inputToValue('text','formatMinute1',dd2.Format('mm'));//mm
      inputToValue('text','formatMinute2',dd2.Format('m'));//m
      inputToValue('text','formatSecond1',dd2.Format('SS'));//SS/ss
      inputToValue('text','formatSecond2',dd2.Format('s'));//S/s
      //日期天数差:日期格式YYYY-MM-dd
      var s_date = $("input[type='text'][name='s_date']").val();
      var e_date = $("input[type='text'][name='e_date']").val();
      function daysBetween(DateOne,DateTwo)
      {
        var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));
        var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);
        var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));
        var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'));
        var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1);
        var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-'));
        var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000);
        return Math.abs(cha);
      }
      inputToValue('text','diff_date',daysBetween(s_date,e_date));
      //日期计算,返回一段日期时间后的对象
      Date.prototype.DateAdd = function(strInterval, Number) {
        var dtTmp = this;
        switch (strInterval) {
          case 's' :return new Date(Date.parse(dtTmp) + (1000 * Number));
          case 'n' :return new Date(Date.parse(dtTmp) + (60000 * Number));
          case 'h' :return new Date(Date.parse(dtTmp) + (3600000 * Number));
          case 'd' :return new Date(Date.parse(dtTmp) + (86400000 * Number));
          case 'w' :return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
          case 'q' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number*3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());//一个季度
          case 'm' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());//一个月
          case 'y' :return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        }
      }
      var dd3 = new Date();
      inputToValue('text','date_now',dd3.DateAdd('s',0));
      inputToValue('text','second_now',dd3.DateAdd('s',2));//2秒后
      inputToValue('text','hour_now',dd3.DateAdd('h',2));//2小时后
      inputToValue('text','day_now',dd3.DateAdd('d',2));//2天后
      inputToValue('text','week_now',dd3.DateAdd('w',2));//2周后
      inputToValue('text','quarter_now',dd3.DateAdd('q',1));//一季度后
      inputToValue('text','month_now',dd3.DateAdd('m',1));//一个月后
      inputToValue('text','year_now',dd3.DateAdd('y',1));//一个年后
      //重载系统的toString方法
      Date.prototype.toString = function(showWeek)
      {
        var myDate= this;
        var str = myDate.toLocaleDateString();//保留年/月/日
        if (showWeek)
        {
          var Week = ['日','一','二','三','四','五','六'];
          str += ' 星期' + Week[myDate.getDay()];
        }
        return str;
      }
      var dd4 = new Date();
      inputToValue('text','reset_string',dd4.toString("一"));
      //日期合法性校验,格式:YYYY-MM-DD或者YYYY/MM/DD,特殊情况如YYYY-MM/DD也能通过,后期处理
      function checkAndGetValue(DateStr)
      {
        var sDate=DateStr.replace(/(^\s+|\s+$)/g,''); //去两边空格;
        if(sDate=='')
          return false;
        //正则表达式
        patter = /^[\d]{4,4}[-/]{1}[\d]{1,2}[-/]{1}[\d]{1,2}$/;//不能加双引号
        if(patter.test(sDate)){
          var t = new Date(sDate.replace(/\-/g,'/'));
          var ar = sDate.split(/[-/:]/);
          if(ar[0] != t.getFullYear() || ar[1] != t.getMonth()+1 || ar[2] != t.getDate()){
            return false;
          }else{
            return ar.join("-");
          }
        }else{
          return false;
        }
      }
      $("input[type='button'][name='checkInputDate']").click(function(){
        $_a = $("input[type='text'][name='checkDate']");
        var getCheckDateValue = $_a.val();
        if(checkAndGetValue(getCheckDateValue)){
          alert("校验通过:" + checkAndGetValue(getCheckDateValue));
        }else{
          $_a.val("");//不通过,清空输入的值
          alert("校验不通过");
        }
      });
      //日期合法性校验 YYYY-MM-DD HH:II:SS
      function CheckDateTime(DateStr)
      {
        var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
        var r = DateStr.match(reg);
        if(r==null) return false;
        r[2] = r[2]-1;
        var d = new Date(r[1],r[2],r[3],r[4],r[5],r[6]);
        if(d.getFullYear() != r[1]) return false;
        if(d.getMonth() != r[2]) return false;
        if(d.getDate() != r[3]) return false;
        if(d.getHours() != r[4]) return false;
        if(d.getMinutes() != r[5]) return false;
        if(d.getSeconds() != r[6]) return false;
        return true;
      }
      $("input[type='button'][name='checkInputDate1']").click(function(){
        $_a = $("input[type='text'][name='checkDate1']");
        var getCheckDateValue1 = $_a.val();
        if(CheckDateTime(getCheckDateValue1)){
          alert("校验通过");
        }else{
          $_a.val("");//不通过,清空输入的值
          alert("校验不通过");
        }
      });
      //把日期分割成数组
      Date.prototype.toArray = function()
      {
        var myDate = this;
        var myArray = Array();
        myArray[0] = myDate.getFullYear();
        myArray[1] = myDate.getMonth() + 1;
        myArray[2] = myDate.getDate();
        myArray[3] = myDate.getHours();
        myArray[4] = myDate.getMinutes();
        myArray[5] = myDate.getSeconds();
        return myArray;
      }
      var dd5 = new Date();
      $("input[name='splitDate']").val(dd5.toArray()[0]);
      //通用函数
      function inputToValue(type,name,value){
        $("input[type="+ type +"][name="+ name +"]").val(value);
      }
    })
  </script>
</body>
</html>

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun测试上述代码运行效果。

PS:这里再为大家推荐几款比较实用的天数计算在线工具供大家使用:

在线日期/天数计算器:
http://tools.3water.com/jisuanqi/date_jisuanqi

在线日期计算器/相差天数计算器:
http://tools.3water.com/jisuanqi/datecalc

在线日期天数差计算器:
http://tools.3water.com/jisuanqi/onlinedatejsq

在线天数计算器:
http://tools.3water.com/jisuanqi/datejsq

希望本文所述对大家JavaScript程序设计有所帮助。

jQuery 相关文章推荐
jQuery实现radio第一次点击选中第二次点击取消功能
May 15 jQuery
一个有意思的鼠标点击文字特效jquery代码
Sep 23 jQuery
jQuery实现点击自身以外区域关闭弹出层功能完整示例【改进版】
Jul 31 jQuery
jQuery 获取除某指定对象外的其他对象 ( :not() 与.not())
Oct 10 jQuery
jquery使用FormData实现异步上传文件
Oct 25 jQuery
jQuery实现的卷帘门滑入滑出效果【案例】
Feb 18 jQuery
jQuery事件委托代码实践详解
Jun 21 jQuery
JavaScript自动生成 年月范围 选择功能完整示例【基于jQuery插件】
Sep 03 jQuery
jquery.tagsinput.js实现记录checkbox勾选的顺序
Sep 21 jQuery
javascript/jquery实现点击触发事件的方法分析
Nov 11 jQuery
jQuery实现滑动星星评分效果(每日分享)
Nov 13 jQuery
jQuery实现全选按钮
Jan 01 jQuery
jQuery使用$.extend(true,object1, object2);实现深拷贝对象的方法分析
Mar 06 #jQuery
[jQuery] 事件和动画详解
Mar 05 #jQuery
jQuery实现的导航条点击后高亮显示功能示例
Mar 04 #jQuery
Vue CLI3.0中使用jQuery和Bootstrap的方法
Feb 28 #jQuery
jQuery.parseJSON()函数详解
Feb 28 #jQuery
jQuery each和js forEach用法比较
Feb 27 #jQuery
jQuery中each和js中forEach的区别分析
Feb 27 #jQuery
You might like
PHP学习笔记之数组篇
2011/06/28 PHP
php正则表达式使用的详细介绍
2013/04/27 PHP
解析argc argv在php中的应用
2013/06/24 PHP
php将一维数组转换为每3个连续值组成的二维数组
2016/05/06 PHP
JavaScript关于select的相关操作说明
2010/01/13 Javascript
jquery DOM操作 基于命令改变页面
2010/05/06 Javascript
Javascript面向对象编程
2012/03/18 Javascript
js+jquery实现图片裁剪功能
2015/01/02 Javascript
JavaScript中诡异的delete操作符
2015/03/12 Javascript
浅谈JS中json数据的处理
2016/06/30 Javascript
浅谈js构造函数的方法与原型prototype
2016/07/04 Javascript
AngularJS实现的回到顶部指令功能实例
2017/05/17 Javascript
详解express + mock让前后台并行开发
2018/06/06 Javascript
利用jsonp解决js读取本地json跨域的问题
2018/12/11 Javascript
vue动态合并单元格并添加小计合计功能示例
2020/11/26 Vue.js
[02:46]2014DOTA2国际邀请赛 选手为你解读比赛MVP充满梦想
2014/07/09 DOTA
[02:09]2018DOTA2亚洲邀请赛TNC赛前采访
2018/04/04 DOTA
python字符串的常用操作方法小结
2016/05/21 Python
Python实现合并同一个文件夹下所有PDF文件的方法示例
2018/04/28 Python
django queryset相加和筛选教程
2020/05/18 Python
python如何求100以内的素数
2020/05/27 Python
基于python纯函数实现井字棋游戏
2020/05/27 Python
python绕过图片滑动验证码实现爬取PTA所有题目功能 附源码
2021/01/06 Python
新加坡时尚网上购物:Zalora新加坡
2016/07/26 全球购物
LA MER海蓝之谜美国官网:传奇面霜
2016/08/27 全球购物
Mio Skincare美国官网:身体紧致及孕期身体护理
2017/03/05 全球购物
奥地利领先的在线药房:SHOP APOTHEKE
2019/10/07 全球购物
过滤器的用法
2013/10/08 面试题
学校招生宣传广告词
2014/03/19 职场文书
中韩经贸翻译专业大学生职业生涯规划范文
2014/09/18 职场文书
学校四风问题对照检查材料思想汇报
2014/09/26 职场文书
团党委领导干部党的群众路线教育实践活动个人对照检查材料思想汇
2014/10/05 职场文书
租赁协议书
2015/01/27 职场文书
三八红旗手主要事迹材料
2015/11/04 职场文书
4种非常实用的python内置数据结构
2021/04/28 Python
PostgreSQL逻辑复制解密原理解析
2022/09/23 PostgreSQL