js-Date和时间格式化

本文详细介绍了如何使用JavaScript进行时间格式化和时间戳格式化,并通过timeago组件实现时间显示的自动化更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:zccst

日期函数同PHP,shell,perl一样。用法可直接参数手册。关键是积累吧。


timeago需要的时间格式

//时间格式化yyyy-MM-dd hh:mm:ss
Date.prototype.format = function(format)
{
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(format))
{
format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o)
{
if(new RegExp("("+ k +")").test(format))
{
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
}
}
return format;
}



时间戳格式化+timeago

function dateFormat(timestamp) {
// 今天
var today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var oneday = 1000 * 60 * 60 * 24;
var yesterday = new Date(today - oneday);
var beforeyesterday = new Date(yesterday - oneday);

var date = new Date(timestamp-0);
var now = new Date();
var time = (now.valueOf() -date.valueOf() ) /1000;
var text = "";
if(date.valueOf() <= beforeyesterday.valueOf()){return date.format("yyyy-MM-dd hh:mm"); };
if(yesterday.valueOf() >= date.valueOf() && date.valueOf() >= beforeyesterday.valueOf()){return "前天 "+date.format("hh:mm")}
if(today.valueOf() >= date.valueOf() && date.valueOf() >= yesterday.valueOf()){return "昨天 "+date.format("hh:mm")}
if(time >= 3600 && date.valueOf() >= today.valueOf()){return Math.round(time / 60 /60)+"小时前";}
if(time >= 60 && time < 3600){return Math.round(time/60)+"分钟前";}
if(time < 60){return "刚刚"; };

return text;
}


手工更新是不会自己更新的,(timeago组件是可以自动更新的)
所以需要每隔10秒钟更新一下

//刷新时间
setInterval(function() {
$(".ctime").each(function() {
//$(this).html(dateFormat($(this).attr("data-value")));
});
}, 10000);




一、输出当前时间
var d2 = new Date();
var cur_year = d2.getFullYear();
var cur_month = d2.getMonth() + 1;
if( cur_month < 10){
cur_month = '0' + cur_month;
}

alert(cur_year + "-" + cur_month + "-" + d2.getDate());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值