封装时间篇-相对时间

223 阅读1分钟

不通过下包怎么获取时间呢?

在编程中,总会遇到各种各样的获取时间的要求,下面我们来看一下获取不同时间格式的方法有哪些?如果不记得的话建议收藏哦!

当前时间集

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script>
    /**
 * 中国标准时间处理成 2018-05-01 00:00:00  这种格式
 * @param {中国标准时间} time
 * @param {一状态 } state   ture要时分秒  false不要时分秒
 */
 const dateToTime = function (time, state) {
    const date = new Date(time)
    const Y = date.getFullYear() + '' // 这里加上''是为了将number类型转换成string类型,方便timeAdd0()方法做判断
    const M = date.getMonth() + 1 + ''
    const D = date.getDate() + ''
    const h = date.getHours() + ''
    const m = date.getMinutes() + ''
    const s = date.getSeconds() + ''
    if (state) {
      return (
        Y +
          '-' +
          timeAdd0(M) +
          '-' +
          timeAdd0(D) +
          ' ' +
          timeAdd0(h) +
          ':' +
          timeAdd0(m) +
          ':' +
          timeAdd0(s)
      )
    } else {
      return Y + '-' + timeAdd0(M) + '-' + timeAdd0(D)
    }
    // 三元表达式判断返回值
    // return state
    //   ? Y + timeAdd0(M) + timeAdd0(D) + timeAdd0(h) + timeAdd0(m) + timeAdd0(s)
    //   : timeAdd0(Y) + timeAdd0(M) + timeAdd0(D);
    function timeAdd0 (str) {
      if (str.length <= 1) {
        str = '0' + str
      }
      return str
    }
  }
  // 获取当前日期时间 Sat Apr 09 2022 19:26:26 GMT+0800 (中国标准时间)
  console.log(new Date())

  // 获取当年月日 2022/4/9
  console.log(new Date().toLocaleDateString())//2020/11/4

  // 获取当前日期 2020-11-04 18:20:49
  console.log(dateToTime('Sat Apr 09 2022 19:26:26 GMT+0800',true));
  
  //获取当前时间 19:31:50
  console.log(new Date().toLocaleTimeString())
  console.log(new Date().toLocaleTimeString('chinese', { hour12: false }))

  // 获取当前年 2022
  console.log(new Date().getFullYear())

  //获取当前月份 
  console.log(new Date().getMonth()+1)

  // 获取当前日 
  console.log(new Date().getDate())

  // 获取一个星期的某一天,当前是星期几
  console.log(new Date().getDay())

  // 获取时
  console.log(new Date().getHours())

  // 获取分
  console.log(new Date().getMinutes())

  // 获取秒
  console.log(new Date().getSeconds())

  // 获取毫秒
  console.log(new Date().getMilliseconds())

  // 获取日期 1970.01.01 距现在的毫秒数
  console.log(new Date().getTime())
  </script>
</head>
<body>
    
</body>
</html>

相对时间

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
            //获取多久以前,比如1秒前、一分钟前、一天前,等等
        function getTimeFormat(startTime) {
            var startTimeMills = startTime.getTime();
            var endTimeMills = new Date().getTime();
            var diff = parseInt((endTimeMills - startTimeMills) / 1000);
            /* 秒  */var day_diff = parseInt(Math.floor(diff / 86400));
            /*  天 */ var buffer = Array(); 
            if (day_diff < 0) {
                    return "[error],时间越界...";
                } else {
              if (day_diff == 0 && diff < 60) {
                   if (diff <= 0) diff = 1; buffer.push(diff + "秒前"); 
                } else if (day_diff == 0 && diff < 120) { 
                    buffer.push("1 分钟前"); 
                } else if (day_diff == 0 && diff < 3600) { 
                    buffer.push(Math.round(Math.floor(diff / 60)) + "分钟前"); 
                } else if (day_diff == 0 && diff < 7200) { 
                     buffer.push("1小时前"); 
                } else if (day_diff == 0 && diff < 86400) {
                     buffer.push(Math.round(Math.floor(diff / 3600)) + "小时前"); 
                } else if (day_diff == 1) {
                     buffer.push("1天前"); 
                } else if (day_diff < 7) {
                     buffer.push(day_diff + "天前"); 
                } else if (day_diff < 30) {
                 buffer.push(Math.round(Math.floor(day_diff / 7)) + " 星期前"); 
                } else if (day_diff >= 30 && day_diff <= 179) { 
                    buffer.push(Math.round(Math.floor(day_diff / 30)) + "月前"); 
             } else if (day_diff >= 180 && day_diff < 365) {
                  buffer.push("半年前"); 
            } else if (day_diff >= 365) {
                 buffer.push(Math.round(Math.floor(day_diff / 30 / 12)) + "年前");
                 }
             } return buffer.toString();
        }
        /*返回 1970 年 1 月 1 日至今的毫秒数。*/ 
            function getMillTime(date){ return transformDate(date).getTime(); }

         /* 日期转换 */
            function transformDate(date){ 
                if(typeof date =="string"){ 
                    return new Date(date.replace(/-/ig,"/").replace("T"," ")); 
                }else{
                    return date; 
                }
             } 
            /*返回相差的毫秒数。*/
            function getDifMillSeconds(date1,date2){ 
                var stimes = getMillTime(transformDate(date1));
            /*返回相差的秒数。*/
                var etimes = getMillTime(transformDate(date2)); 
                return etimes - stimes;
            }
             
             /*返回相差的分。*/
             function getDifSeconds(date1,date2){ return Math.floor(getDifMillSeconds(date1,date2) / 1000);} 

             /*返回相差的小时。*/
             function getDifMinutes(date1,date2){ return Math.floor(getDifMillSeconds(date1,date2)/(1000*60));}

             /*返回相差的天数。*/
             function getDifHours(date1,date2){ return Math.floor(getDifMillSeconds(date1,date2)/(1000*60*60));}

             /*返回相差的月份。*/
             function getDifDays(date1,date2){  var times = getDifSeconds(date1,date2); return Math.ceil(times/(3600 * 24));}
            
             /*获取相差的年份*/
             function getDifMonths(date1,date2){  var times = getDifDays(date1,date2); return Math.floor(times/30);}

             /*获取年份*/
             function getDifYear(date1,date2){ var times = getDifDays(date1,date2); return Math.floor(times/365);}

             /*获取月*/
             function getYear(date){ return transformDate(date).getFullYear();}

             /*获取日*/ 
             function getMonth(date){ var month = transformDate(date).getMonth()+1; return month>9 ? month : "0"+month; } 

              /*获取今天星期几,如果为0代表星期日*/ 
             function getDay(date){ var day = transformDate(date).getDate(); return day >9 ? day : "0"+day; } 

             /*获取时*/ 
             function getWeek(date){ return transformDate(date).getDay(); }
             function getWeekChinese(date){
                  var weekdays = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']; 
               return weekdays[getWeek(date)];
                } 

             /*12小时制时*/
             function getHour(date){ var hour = transformDate(date).getHours(); return hour >9 ? hour : "0"+hour; }  

             /*分*/ 
             function getHour12(date){ var hour = transformDate(date).getHours(); return hour%12 == 0 ? 12 : hour % 12; } 

             /*秒*/ 
             function getMinute(date){ var minutes = transformDate(date).getMinutes(); return minutes >9 ? minutes : "0"+minutes; } 

             /*毫秒*/
             function getSecond(date){ var seconds = transformDate(date).getSeconds(); return seconds >9 ? seconds : "0"+seconds; } 

             /*获取今天在当年是第几季度*/ 
             function getMillisecond(date){ return transformDate(date).getMilliseconds(); }  

             /*根据输入的日期获取该年的第一天*/
             function getPeriod(date){ var month = getMonth(date)*1; return Math.floor((month+3)/3); } 

             /*获取输入日期是当年中的第几天*/
             function getFirstDayOfYear(date){ var year = getYear(date); var dateString = year+"-01-01 00:00:00"; return dateString;}


             function getDayOfYear(date){ return Math.ceil(getDifDays(getFirstDayOfYear(date),date));}




            console.log(Date.now(),'当前时间戳');
            console.log(getMillTime('2020-11-04 18:20:49'),'指定时间戳');
            console.log('今天是'+transformDate(1649503354286),11);

            var date1 = transformDate("2016/8/10 09:12:45");
            var date2 = transformDate("2016/8/10 08:12:45");
            console.log('1个小时内有' + getDifSeconds(date2,date1)+'分钟','相对分钟 ');           
            console.log('1天有' + getDifHours(date2,date1) + '个小时','相对小时');

            date1 = transformDate("2016/8/11 08:12:45");
            date2 = transformDate("2016/7/11 08:12:45");
            console.log('7月份有' + getDifDays(date2,date1) + '天','相对天');

            date1 = transformDate("2016/8/11 08:12:45");
            date2 = transformDate("2015/8/11 08:12:45");
            console.log('一年为' + getDifMonths(date2,date1) + '个月','相对月'); 

            date1 = transformDate("2016/8/11 08:12:45");
            date2 = transformDate("2010/8/11 08:12:45");
            console.log('2010年和2016年相差' + getDifYear(date2,date1) + '年','相对年');

            var date = new Date();console.log('今年是' + getYear(date) + '年','获取当前年');
            console.log('本月是' + getMonth(date) + '月','获取当前月');
            console.log('今天是' + getDay(date) + '日' ,'获取当前日');
            console.log('今年的第一天是' + getFirstDayOfYear(date),'获取当前第一天');
            console.log('今年是星期' + getWeek(date),'获取当前日期星期');
            console.log('今年是' + getWeekChinese(date),'获取当前年');
            //    获取多久以前
            console.log('2022/4/8 09:10:45是' + getTimeFormat(transformDate("2016/8/16 09:10:45")));
            console.log('1995/8/16是' + getTimeFormat(transformDate("1995/8/16")));
    </script>
</head>
<body>
    
</body>
</html>