JavaScript时间格式化

一、把时间格式化为多少秒、分钟、小时、天、月、年之前

function friendlyDate(timestamp) {
	var formats = {
		'year': '%n% 年前',
		'month': '%n% 月前',
		'day': '%n% 天前',
		'hour': '%n% 小时前',
		'minute': '%n% 分钟前',
		'second': '%n% 秒前',
	};

	var now = Date.now();

	var seconds = Math.floor((now - timestamp) / 1000);
	var minutes = Math.floor(seconds / 60);
	var hours = Math.floor(minutes / 60);
	var days = Math.floor(hours / 24);
	var months = Math.floor(days / 30);
	var years = Math.floor(months / 12);

	var diffType = '';
	var diffValue = 0;
	if (years > 0) {
		diffType = 'year';
		diffValue = years;
	} else {
		if (months > 0) {
			diffType = 'month';
			diffValue = months;
		} else {
			if (days > 0) {
				diffType = 'day';
				diffValue = days;
			} else {
				if (hours > 0) {
					diffType = 'hour';
					diffValue = hours;
				} else {
					if (minutes > 0) {
						diffType = 'minute';
						diffValue = minutes;
					} else {
						diffType = 'second';
						diffValue = seconds === 0 ? (seconds = 1) : seconds;
					}
				}
			}
		}
	}
	return formats[diffType].replace('%n%', diffValue);
}

二、时间格式化以指定格式返回时间(yyyy-MM-dd hh:mm:ss)

function formatDate(dateTime,formatValue){
    let timer = new Date(dateTime);
    let year = timer.getFullYear();
    let month = timer.getMonth()+1;
    let date = timer.getDate();
    let hour = timer.getHours();
    let minute = timer.getMinutes();
    let second = timer.getSeconds();
    if(month<10)month = "0"+month;
    if(date<10)date = "0"+date;
    if(hour<10)hour = "0"+hour;
    if(minute<10)minute = "0"+minute;
    if(second<10)second = "0"+second;
    let result = null;
    switch(formatValue){
        case "yyyy-MM-dd hh:mm:ss": result = year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
            break;
        case "yyyy/MM/dd hh:mm:ss": result = year+"/"+month+"/"+date+" "+hour+":"+minute+":"+second;
            break;
        case "yyyy-MM-dd": result = year+"-"+month+"-"+date;
            break;
        case "yyyy/MM/dd": result = year+"/"+month+"/"+date;
            break;
        case "hh:mm:ss": result = hour+":"+minute+":"+second;
            break;
        default: result = "格式错误";
    }
    return result;
}

//console.log(formatDate(new Date,"yyyy-MM-dd hh:mm:ss"));
//console.log(formatDate(new Date,"yyyy/MM/dd hh:mm:ss"));
//console.log(formatDate(new Date,"yyyy-MM-dd"));
//console.log(formatDate(new Date,"yyyy/MM/dd"));
//console.log(formatDate(new Date,"hh:mm:ss"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员咚咚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值