Date时间的格式的封装

第三章

在开发中,我们经常会遇到对于时间的进行封装

这个我不得不提一下微信小程序中自带封装, 不得不说, 写的很好, 值得我学习

工整, 美观, (或许这就是代码之美吧)

  • 格式化:
const formatTime = date => {
    date = new Date(date)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
new Date().toLocaleString() //本地时间

在这里插入图片描述

  • new Date().toLocaleDateString().split('/').join('-')

感 觉 这 个 更 加 是 无 敌 感觉这个更加是无敌
与上面这个效果是一样的

let d = new Date();
d.toJSON().substr(0,10)+' '+d.toTimeString().substr(0,8)

当然除了substr()字符串方法, 也有substring(), 与slice(), 方法, (slice 与在字符串与数组中均可使用)

  • 另一种方法

join(’-’), 既可以用在数组中, 也可以用在字符串中

const formatDate = date => {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month; //通过字符串的长度判断
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
  • 倒计时:
// 倒计时处理
const getOverTime = time => {
    let a = new Date(time).getTime();
    let c = a - Date.now();
    if (c <= 0) {
        return false
    }
    let days = Math.floor(c / (24 * 3600 * 1000));
    let leave1 = c % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000));
    let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000));
    let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000);
    return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
}
  • 判断时间
    这个写的不是很好, 应该可以理由高阶函数在对这个进行简化
function getDateDiff(dateTimeStamp) {
  const minute = 1000 * 60;
  const hour = minute * 60;
  const day = hour * 24;
  const month = day * 30;
  const year = day * 365;
  const now = new Date().getTime();
  const diffValue = now - dateTimeStamp;
  if(diffValue < 0){
   
      return '数据出错';
  }

  const yearC = diffValue / year;
  const monthC = diffValue / month;
  const weekC = diffValue / (7 * day);
  const dayC = diffValue / day;
  const hourC = diffValue / hour;
  const minC = diffValue / minute;
  let result = '';



  if(yearC >= 1){
      result = parseInt(yearC) + '年以前';
  }else if(monthC >= 1){
      result = parseInt(monthC) + '个月前';
  }else if(weekC >= 1){
      result = parseInt(weekC) + '星期前';
  }else if(dayC >= 1){
      result = parseInt(dayC) + '天前';
  }else if(hourC >= 1){
      result = parseInt(hourC) + '小时前';
  }else if(minC >= 5){
      result = parseInt(minC) + '分钟前';
  }else{
      result = '刚刚发表';
  }
  return result;
}

输出各种格式的时间(设置好时间格式)

Date.prototype.format = function(fmt){
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };

  if(/(y+)/.test(fmt)){
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
        
  for(var k in o){
    if(new RegExp("("+ k +")").test(fmt)){
      fmt = fmt.replace(
        RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
    }       
  }

  return fmt;
}

(new Date().format(‘yyyy年MM月dd日’));
(new Date().format(‘MM/dd/yyyy’));
(new Date().format(‘yyyyMMdd’));
(new Date().format(‘yyyy-MM-dd hh:mm:ss’));

设置一个开始与结束时间函数

getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 30;
				} else if (type === 'end') {
					year = year + 20;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},

高级的封装

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(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串,转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

module.exports = {
	formatTime,
	formatLocation,
	dateUtils
}

5/22
返回今天是星期几

 function retrunDay() {
      return '今天星期'+'日一二三四五六'.charAt(new Date().getDay())
      
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值