JavaScript - 时间相关

  • 基本用法:
var myDate = new Date(); //Sat Nov 19 2016 10:34:56 GMT+0800 (中国标准时间)
myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1月)
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)
myDate.getMilliseconds(); //获取当前毫秒数(0-999)
myDate.toLocaleDateString(); //获取当前日期
var mytime=myDate.toLocaleTimeString(); //获取当前时间
myDate.toLocaleString( ); //获取日期与时间

//获取当前时间戳:
//1.
var starttime = (new Date()).valueOf();
//2.
var timestamp=new Date().getTime();
//3.
var timestamp =Date.parse(new Date());   //1479523820000 //此法将毫秒转换成了 000 不够精确

new Date() 参与计算会自动转换为从1970.1.1开始的毫秒数

//将字符串形式的日期转换成日期对象
var t=new Date(Date.parse("2016-11-19"));

//将字符串形式的日期转换成日期对象
var strTime="2016-11-19"; //字符串日期格式           
var date= new Date(Date.parse(strTime.replace(/-/g,"/"))); //转换成Data();
var month=date.getMonth()+1; //获取当前月份


//带有参数的 new Date([arguments list]);
//参数有以下5种:
new Date("month dd,yyyy hh:mm:ss");
new Date("month dd,yyyy");
new Date(yyyy,mth,dd,hh,mm,ss); //此处传递的参数 必须是整型
new Date(yyyy,mth,dd);
new Date(ms);  //参数表示的是需要创建的时间和 GMT时间1970年1月1日之间相差的毫秒数

/*
其中参数含义:
month:用英文 表示月份名称,"January","February","March","April","May","June","July","August","September","October","November","December"
mth:用整数表示月份,1月到12月
dd:表示一个 月中的第几天,从1到31 
yyyy:四位数表示的年份 
hh:小时数,从0(午夜)到23(晚11点)
mm: 分钟数,从0到59的整数 
ss:秒数,从0到59的整数 
ms:毫秒数,为大于等于0的整数 
*/

//示例
new Date("January 12,2006 22:19:35"); 
new Date("January 12,2006"); 
new Date(2006,0,12,22,19,35); 
new Date(2006,0,12); 
new Date(1137075575000); 
  • 获取某月天数
//获取某月天数
function getMonthDay(date){
    date=date||new Date();
    if(typeof date==='string'){
        date=new Date(date);
    }
    date.setDate(32); //自动减去当月的天数 
    return 32-date.getDate();//date.getDate()会返回一个减去当月天数的值 剩余值就是当月天数
}
  • 日期格式化
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//将个位数补上0
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
  • 时间格式化
function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  var hour = parseInt(time / 3600)
  time = time % 3600
  var minute = parseInt(time / 60)
  time = time % 60
  var second = time

  return ([hour, minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}
  • 距离现在的时间 time to now
let timeToNow = (time) => {
  const t = parseFloat(new Date - new Date(time)) / 1000;
  let str;
  if (!t) return;
  if (t > 60 && t < 3600 ) {
    str = `${parseInt(t / 60.0, 10)}分钟前`;
  } else if (t >= 3600 && t < 86400) {
    str = `${parseInt(t / 3600.0, 10)}小时前`;
  } else if (t >= 86400 && t < 86400 * 30) {
    str = `${parseInt(t / 86400.0, 10)}天前`;
  } else if (t >= 86400 * 30 && t < 86400 * 365) {
    str = `${parseInt(t / (86400.0 * 30), 10)}个月前`;
  } else if (t >= 86400 * 365) {
    str = `${parseInt(t / (86400.0 * 365), 10)}年前`;
  } else {
    str = `${parseInt(t, 10)}秒前`;
  }
  return str;
}
  • 获取从当前时间到指定日期的间隔时间
function getChIntv(data){
    var str = data.split("-").join(","); // 2017,05,01
    var date = new Date(str);
    var nowDate = new Date();
    var diff = date - nowDate; // 总时间差
    var getDay = Math.floor( diff / (24 * 60 * 60 * 1000) );
    var getHours = Math.floor( diff / (60 * 60 * 1000) ) % 24;
    var getMinutes = Math.floor( diff / (60 * 1000) ) % 60;
    var getSeconds = Math.floor( diff / 1000) % 60;
    return "距离五一还有" + getDay + "天" + getHours + "小时" + getMinutes + "分钟" + getSeconds + "秒";
}
var str = getChIntv("2017-05-01");
console.log(str);
  • 计算两个时间差 diffDate
  /**
   * 
   * @param {*} time1 a Date object or Date params
   * @param {*} time2 a Date object or Date params
   * @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second']
   * @param {*} exact get exact day diff
   */
  function diffDate (time1, time2, unit='day', exact = false) {
    let date1 = new Date(time1)
    let date2 = new Date(time2)
    if (unit === 'year') {
      return date2.getFullYear() - date1.getFullYear()
    }
    if (unit === 'month') {
      let diffYear = date2.getFullYear() - date1.getFullYear()
      return (date2.getMonth() - date1.getMonth()) + 12 * diffYear
    }
    if (!exact && unit === 'day') {
      date1 = new Date(format(date1, 'yyyy-MM-dd'))
      date2 = new Date(format(date2, 'yyyy-MM-dd'))
    }
    let timeStampUnit = getTimeStampUnit(unit)
    return parseInt((date2.getTime() - date1.getTime()) / timeStampUnit)
  }
  • 把hh-mm-dd格式数字日期改成中文日期
function getChsDate(data){
    var str = data.split("-"); // ["2015", "01", "08"]
    var dateArr = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一"];
    var year = str[0];
    var month = str[1];
    var day = str[2];
    var getYear = dateArr[ parseInt(year[0]) ] + dateArr[ parseInt(year[1]) ] + dateArr[ parseInt(year[2]) ] + dateArr[ parseInt(year[3]) ];
    var getMonth = dateArr[ parseInt(month * 1 ) ]; 
    var getDay = dateArr[ parseInt(day * 1 ) ];
    return getYear +'年'+getMonth+'月'+getDay+'日';
}
var str = getChsDate('2015-01-08');
console.log(str);  // 二零一五年一月八日
  • 参数为时间对象毫秒数的字符串格式,返回值为字符串。

假设参数为时间对象毫秒数t,根据t的时间分别返回如下字符串: 刚刚( t 距当前时间不到1分钟时间间隔) 3分钟前 (t距当前时间大于等于1分钟,小于1小时) 8小时前 (t 距离当前时间大于等于1小时,小于24小时) 3天前 (t 距离当前时间大于等于24小时,小于30天) 2个月前 (t 距离当前时间大于等于30天小于12个月) 8年前 (t 距离当前时间大于等于12个月)

function getPastTime(t){
 var pastTime = new Date() - t;
 if( pastTime <  (60 * 1000) ){
    return('刚刚');
 }else if(pastTime < (60 * 60 * 1000) ){
     return( Math.floor( pastTime / (60 * 1000) ) % 60 + '分钟前');
 }else if( pastTime < (24 * 60 * 60 * 1000) ){
     return(Math.floor( pastTime / (60 * 60 * 1000) ) % 24 +'小时前');
 }else if( pastTime < (30 * 24 * 60 * 60 * 1000) ){
     return(Math.floor( pastTime / (24 * 60 * 60 * 1000) ) % 30 +'天前');
 }else if( pastTime < (12 * 30 * 24 * 60 * 60 * 1000) ){
     return(Math.floor( pastTime / (30 * 24 * 60 * 60 * 1000) ) % 12 +'个月前');
 }else{
     return(Math.floor( pastTime / (12 * 30 * 24 * 60 * 60 * 1000) ) +'年前');
 }
}
getPastTime('1492350564250');
  • 关于GMT , UTC
    GMT(格林尼治标准时间)是一些欧洲和非洲国家正式使用的时间,UTC是国际标准。这两个时间一般情况是相等的。中国处于东八区,与UTC时间相差8个小时,也就是说UTC时间00:00:00的时候,我们的时间是08:00:00。
    为了避免这种现象,对于任何的输入,都统一生成一个UTC时间,那么新建一个date函数,这个Date函数用于根据传入的时间模板,生成一致的时间。'yyyy-MM-dd'格式的时间模板new出来的date是本地时间,所以用正则表达式匹配一下/^\d{4}(-\d{2}){0,2}$/.test(date)。重写一个Date构造函数,用于根据输入的时间模板生成一致的时间。
//本地时间转换成UTC时间
export function UtcDate(date = "") {
  let isDate = (typeof date === 'object') && (date instanceof Date)
  if (isDate) return date
  let localDate

  if (Object.prototype.toString.apply(date).slice(-7, -1) === 'String') {
    date = date.replace(/T/, ' ').replace(/-/g, '/')
  }
  try {
    localDate = date === undefined ? new Date() : new Date(date)
  } catch (e) {
    console.error(e)
  }
  if (date && /^\d{4}([-\/]\d{1,2}){0,2}$$/.test(date)) {
    let timeZoneOffset = localDate.getTimezoneOffset()
    let utcTimeStamp = localDate.getTime() + timeZoneOffset * 60 * 1000
    return new Date(utcTimeStamp)
  }
  return localDate;
}
  • 实用的日期函数库
(function ($) {
function DateUTC (date) {
  if (arguments.length === 0) return new Date()
  if (isDate(date)) return date
  let localDate
  if (Object.prototype.toString.apply(date).slice(-7, -1) === 'String') {
    date = date.replace(/T/, ' ').replace(/-/g, '/')
  }
  try {
    localDate = new Date(date)
  } catch (e) {
    console.error(e)
  }
  // yyyy-MM-dd | yyyy-MM | T:分隔日期和时间 | Z:时区,可以是:Z(UFC)、+HH:mm、-HH:mm
  if (date && /^\d{4}(-\d{2}){0,2}$/.test(date))  {
    let timeZoneOffset = localDate.getTimezoneOffset()
    let utcTimeStamp = localDate.getTime() + timeZoneOffset * 60 * 1000
    return new Date(utcTimeStamp)
  }
  return localDate
}

function format (date, form = 'yyyy-MM-dd') {
  date = DateUTC(date)
  if (!form) return date
  let year = date.getFullYear()
  let month = leftPad(date.getMonth() + 1)
  let day = leftPad(date.getDate())
  let hours = leftPad(date.getHours())
  let minutes = leftPad(date.getMinutes())
  let seconds = leftPad(date.getSeconds())
  return form.replace('yyyy', year).replace('MM', month).replace('dd', day).replace('HH', hours).replace('mm', minutes).replace('ss', seconds)
}

/**
 * 
 * @param {*} time1 a Date object or Date params
 * @param {*} time2 a Date object or Date params
 * @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second']
 * @param {*} exact get exact day diff
 */
function diff (time1, time2, unit='day', exact = false) {
  let date1 = DateUTC(time1)
  let date2 = DateUTC(time2)
  if (unit === 'year') {
    return date2.getFullYear() - date1.getFullYear()
  }
  if (unit === 'month') {
    let diffYear = date2.getFullYear() - date1.getFullYear()
    return (date2.getMonth() - date1.getMonth()) + 12 * diffYear
  }
  if (!exact && unit === 'day') {
    date1 = DateUTC(format(date1, 'yyyy-MM-dd'))
    date2 = DateUTC(format(date2, 'yyyy-MM-dd'))
  }
  let timeStampUnit = getTimeStampUnit(unit)
  return parseInt((date2.getTime() - date1.getTime()) / timeStampUnit)
}
/**
 * 
 * @param {*} date a Date object or Date params
 * @param {*} diff 
 * @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second']
 * for example: dateFrom('2012-02-29', 12, 'month') // Fri Mar 01 2013 00:00:00 GMT+0800 (CST)
 */
function dateFrom(time, diff, unit='day') {
  let date = DateUTC(time)
  if (unit === 'year') {
    let year =  date.getFullYear() + diff
    return DateUTC(date.setFullYear(year))
  }
  if (unit === 'month') {
    let month = date.getMonth() + diff
    return DateUTC(date.setMonth(month))
  }
  let timeStampUnit = getTimeStampUnit(unit)
  return DateUTC(date.getTime() + diff * timeStampUnit)
}

/**
 * use it just like how you new a Date and the second value is the format
 *  if you don't want to format it, set the form to false
 * @param {*} value any params can new a Date
 * @param {*} form 
 * @param {*} UTC 
 */
function dateTemplate ({ date, diff, form, unit } = {}) {
  var _date = !date ? DateUTC() : date
  if (diff) {
    _date = dateFrom(_date, diff, unit)
  }
  if (form) {
    _date = format(_date, form)
  }
  return _date
}


function isDate (date) {
  return date instanceof Date
}

function leftPad (val) {
  return val.toString().padStart(2, '0')
}

function getTimeStampUnit (unit) {
  switch (unit) {
    case 'day':
      return 1000 * 3600 * 24
    case 'hour':
      return  1000 * 3600
    case 'minute':
      return 1000 * 60
    case 'second':
      return 1000
      break
    default:
      return 1
  }
}

$.format = format
$.diff = diff
$.DateUTC = DateUTC
$.dateFrom = dateFrom
$.dateTemplate = dateTemplate
})(window.$);

时钟canvas小程序

/**
 * Created by Administrator on 2017/3/28 0028.
 * source from siwuxie095
 */
var canvas = document.getElementById('dom');
var context = canvas.getContext('2d');
var height = context.canvas.height;
var width = context.canvas.width;
var r = width / 2;
var rem = width/200;

//时钟背景
function drawBackground() {
    context.save();
    context.translate(r, r);
    context.beginPath();
    context.lineWidth = 8*rem;
    context.strokeStyle = "#000"
    context.arc(0, 0, r - 5*rem, 0, 2 * Math.PI, false);
    context.stroke();
    context.closePath();
//遍历小时数
    var houseNumble = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];
    houseNumble.forEach(function (number, i) {
        context.textAlign = 'center';
        context.textBaseline = 'middle'
        context.font = 18*rem+'px Arial'
        var rad = 2 * Math.PI / 12 * i;
        var x = Math.cos(rad) * (r - 30*rem);
        var y = Math.sin(rad) * (r - 30*rem);
        context.fillText(number, x, y);
    })
//定义刻度
    for (var i = 0; i < 60; i++) {
        var rad = 2 * Math.PI / 60 * i;
        var x = Math.cos(rad) * (r - 18*rem);
        var y = Math.sin(rad) * (r - 18*rem);
        context.beginPath();
        if (i % 5 == 0) {
            context.fillStyle = "#000"
            context.arc(x, y, 2*rem, 0, 2 * Math.PI);
        } else {
            context.fillStyle = "#ccc"
            context.arc(x, y, 2*rem, 0, 2 * Math.PI);
        }

        context.fill();
        context.closePath();
    }
}
//定义时针
function drawHour(hour,minute) {
    context.save();
    context.beginPath();
    context.lineWidth = 6*rem;
    context.lineCap = 'round'
    var rad = 2 * Math.PI / 12 * hour;
    var mrad = 2* Math.PI/12/60 * minute;
    context.rotate(rad+mrad);
    context.moveTo(0, 10*rem);
    context.lineTo(0, -r / 2);
    context.stroke();
    context.restore();
}
//定义分针
function drawMinute(minute) {
    context.save();
    context.beginPath();
    context.lineWidth = 3*rem;
    context.lineCap = 'round';
    var rad = 2 * Math.PI / 60 * minute;
    context.rotate(rad);
    context.moveTo(0, 15*rem);
    context.lineTo(0, -r + 34)
    context.stroke();
    context.restore();
}
//定义秒钟
function drawSecond(second) {
    context.save();
    context.beginPath();
    context.lineWidth = 2*rem;
    context.lineCap = 'round';
    context.fillStyle = "red"
    var rad = 2 * Math.PI / 60 * second;
    context.rotate(rad);
    context.moveTo(-2 ,20);
    context.lineTo( 2, 20);
    context.lineTo( 1, -r + 18);
    context.lineTo( -1, -r + 18);
    context.fill();
    context.restore();
}
//画中心点
function drawDot() {
    context.beginPath();
    context.fillStyle = "#fff"
    context.arc(0, 0, 4*rem, 0, 2 * Math.PI, false);
    context.fill();
}
//时间函数,让时钟根据当前时间跳动
function Draw() {
    context.clearRect(0,0,width,height);
    var time= new Date();
    var hour =time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    drawBackground();
    drawHour(hour,minute);
    drawMinute(minute);
    drawSecond(second);
    drawDot();
    context.restore()
}

Draw();
setInterval(Draw,1000);
时钟canvas

效果如下


JavaScript - 时间相关_第1张图片
clock

你可能感兴趣的:(JavaScript - 时间相关)