//时间戳格式化 传参time:指定时间,nowtime:当前时间
function timeTo(time,nowtime) {
var
date
= new Date(time)
var
nowdate
=new Date(nowtime)
var
PY
= date.getFullYear()
var
NY
= nowdate.getFullYear()
var
Y
= date.getFullYear() +
'/'
var
M
= (date.getMonth()+
1
<
10
?
'0'
+(date.getMonth()+
1
) : date.getMonth()+
1
) +
'/'
var
D
= date.getDate() +
''
var
h
= date.getHours() +
'/'
var
m
= date.getMinutes() +
'/'
var
s
= date.getSeconds()
if(
PY
==NY){//判断年份是否是同一年,是的输出格式
08
/
01
不是的话输出格式
2018
/
08
/
01
return M+D
else{
return Y+M+D
//对时间戳进行转化,转化成时间统一xxxx-xx-xx 00:00:00
function timeTotime(time) {
var
date
= new Date(time)
var
Y
= date.getFullYear() +
'-'
var
M
= (date.getMonth()+
1
<
10
?
'0'
+(date.getMonth()+
1
) : date.getMonth()+
1
) +
'-'
var
D
= date.getDate() +
' '
var
h
=
00
+
':'
var
m
=
00
+
':'
var
s
=
00
var
newtime
= Y+M+D+h+m+s
return new Date(newtime).getTime()
//获取传入时间距离当前时间的天数,然后进行判断,状态分为,如果是同一天显示今天,少一天是昨天,
//少两天是前天,超过两天如果在本周显示周几,超过本周显示上周几,超过上周显示真实日期。明天,后天,
//下周同理。
ifDate(1536600501000)
function ifDate(perDate){
var
date
= new Date().getTime()
var
date
= timeTotime(date)
var
perDate
=timeTotime(perDate)
console.log(date,perDate)
var
runTime
=(date-perDate)/
1000
var
year
= Math.floor(runTime /
86400
/
365
)
runTime
= runTime % (
86400
*
365
)
var
month
= Math.floor(runTime /
86400
/
30
)
runTime
= runTime % (
86400
*
30
)
var
day
= Math.floor(runTime /
86400
)
var
day
=parseInt(day)
console.log(day)
var
nowday
= new Date(date).getDay()
if(
nowday
==
0
){//如果为
0
的话,把周日赋值为
7
1
-
7
分别对应周一到周日
var
nowday
=
7
if(
day
==
0
){
console.log('今天')
else if(
day
==
1
){
console.log('昨天')
else if(
day
==
2
){
console.log('前天')
else if(
day
==-
1
){
console.log('明天')
else if(
day
==-
2
){
console.log('后天')
else if(day>2&&day<nowday){//判断是否是当前周而不是上一周
console.log(day,nowday)
var
dayNum
=nowday-day
console.log('周'+(week(dayNum)))
else if(day>2&&day>=nowday&&day<nowday+7){//判断是否是上一周
var
dayNum
=
7
-Math.abs((nowday-day))
console.log('上周'+(week(dayNum)))
else if(day>=nowday+7){//判断是不是超过上一周,显示正常时间格式
console.log(timeTo(perDate,date))
else if(Math.abs(day)<(7-nowday)&&day<0){//判断是否是当前周,不是下一周
var
dayNum
= Math.abs(day)+nowday
console.log('周'+(week(dayNum)))
else if(Math.abs(day)>(7-nowday)&&Math.abs(day)<(7-nowday+7)&&day<0){
var
dayNum
=Math.abs(day)+nowday-
7
console.log('下周'+(week(dayNum)))
else if(Math.abs(day)>(7-nowday+7)&&day<0){//判断是否超过下一周,显示正常格式
console.log(timeTo(perDate,date))
}
复制代码
这个功能感觉还是比较实用的,大家有用到可以拿去用,当然可能需要优化一下,还请大神们自己手动改一改。