js时间戳转为日期格式(yyyy-mm-dd hh:ii:ss w)

本文将为您描述javascript格式化日期时间,js时间戳自定义格式转换,支持年月日时分秒等多种形式组合的日期和时间的方法。

推荐一个JavaScript常用函数库 jutils 的 formatDate 函数

示例

年、月、日、时、分、秒
var date = jutils.formatDate(new Date(1533686888*1000),"YYYY-MM-DD HH:ii:ss");
console.log(date);
// 2019-07-09 19:44:01
年、月、日、周
var date = jutils.formatDate(new Date(1562672641*1000),"YYYY-MM-DD 周W");
console.log(date);
//2019-07-09 周二
月、日、周
var date = jutils.formatDate(new Date(1562672641*1000),"MM-DD 周W");
console.log(date);
//07-09 周二
时、分、秒
var date = jutils.formatDate(new Date(1562672641*1000),"HH:ii:ss");
console.log(date);
//19:44:01

源码

以下是摘自  jutils 时间类的
//时间戳转年月
export const formatDate = (date,formatStr) => {
	let arrWeek = ['日', '一', '二', '三', '四', '五', '六'],
		str = formatStr.replace(/yyyy|YYYY/, date.getFullYear()).replace(/yy|YY/, $addZero(date.getFullYear() % 100,
			2)).replace(/mm|MM/, $addZero(date.getMonth() + 1, 2)).replace(/m|M/g, date.getMonth() + 1).replace(
			/dd|DD/, $addZero(date.getDate(), 2)).replace(/d|D/g, date.getDate()).replace(/hh|HH/, $addZero(date
			.getHours(), 2)).replace(/h|H/g, date.getHours()).replace(/ii|II/, $addZero(date.getMinutes(), 2))
		.replace(/i|I/g, date.getMinutes()).replace(/ss|SS/, $addZero(date.getSeconds(), 2)).replace(/s|S/g, date
			.getSeconds()).replace(/w/g, date.getDay()).replace(/W/g, arrWeek[date.getDay()]);
	return str

}

function $addZero(v, size) {
	for (var i = 0, len = size - (v + "").length; i < len; i++) {
		v = "0" + v
	}
	return v + ""
}
源码:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值