本文实例为大家分享了js显示友好时间的函数代码,供大家参考,具体内容如下
var ct = now_time - time_stamp;
var day = 0;
if (ct < 0)
{
f_time = "【预约】" + f_d.toLocaleString();
}
else if (ct < 60)
{
f_time = Math.floor(ct) + '秒前';
}
else if (ct < 3600)
{
f_time = Math.floor(ct / 60) + '分钟前';
}
else if (ct < 86400)//一天
{
f_time = Math.floor(ct / 3600) + '小时前';
}
else if (ct < 604800)//7天
{
day = Math.floor(ct / 86400);
if (day < 2)
f_time = '昨天';
else
f_time = day + '天前';
}
else
{
day = Math.floor(ct / 86400);
f_time = day + '天前';
}
return f_time;
}
function getd(time1)
{
var da = new Date();
sda = new Date(time1);
var time2 = da.getTime();
var time = 0;
if (time1 > time2)
{
time = time1 - time2;
sda = da;
} else
{
time = time2 - time1;
}
if (time < 1000) return "刚刚";
time = parseInt(time / 1000);
if (time > 86400)
{
var day = parseInt(time / (24 60 60));
if (day == 1)
{
return "昨天(" + sda.getHours() + ":" + sda.getMinutes() + ")";
} else if (day < 30)
{
return day + "天前";
} else if (day < 360)
{
var moth = parseInt(day / 30);
return moth + "个月前";
} else
{
var year = parseInt(day / 360);
return year + "年前";
};
} else if (time > 3600)
{
var hour = parseInt(time / (60 * 60));
return hour + "小时前";
} else if (time > 60)
{
var hour = parseInt(time / 60);
return hour + "分钟前";
} else
{
return time + "秒前";
}
}
有时win7系统会把时间自动显示为带星期的格式,需要对时间格式处理
var d = new Date(Date.parse(q)); return friendly_time(d.getTime() / 1000);