function timeago(dateTimeStamp){
var minute = 1000 * 60 //把分,时,天,周,半个月,一个月用毫秒表示
var hour = minute * 60
var day = hour * 24
var week = day * 7
var halfamonth = day * 15
var month = day * 30
var now = new Date().getTime() //获取当前时间毫秒
console.log(now)
var diffValue = now - dateTimeStamp//时间差
if(diffValue <0){
return
}
var minC = diffValue/minute //计算时间差的分,时,天,周,月
var hourC = diffValue/hour
var dayC = diffValue/day
var weekC = diffValue/week
var monthC = diffValue/month
if(monthC >= 1 &&monthC <= 3){
result = " " + parseInt(monthC) + "月前"
}else if(weekC >= 1 &&weekC <= 3){
result = " " + parseInt(weekC) + "周前"
}else if(dayC >= 1 &&dayC <= 6){
result = " " + parseInt(dayC) + "天前"
}else if(hourC >= 1 &&hourC <= 23){
result = " " + parseInt(hourC) + "小时前"
}else if(minC >= 1 &&minC <= 59){
result =" " + parseInt(minC) + "分钟前"
}else if(diffValue >= 0 &&diffValue <= minute){
result = "刚刚"
}else {
var datetime = new Date()
datetime.setTime(dateTimeStamp)
var Nyear = datetime.getFullYear()
var Nmonth = datetime.getMonth() + 1 <10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1
var Ndate = datetime.getDate() <10 ? "0" + datetime.getDate() : datetime.getDate()
var Nhour = datetime.getHours() <10 ? "0" + datetime.getHours() : datetime.getHours()
var Nminute = datetime.getMinutes() <10 ? "0" + datetime.getMinutes() : datetime.getMinutes()
var Nsecond = datetime.getSeconds() <10 ? "0" + datetime.getSeconds() : datetime.getSeconds()
result = Nyear + "-" + Nmonth + "-" + Ndate
}
return result
}
先说下逻辑:
获得当前的时间戳,和目标时间戳
比对两者的差距
定义展示数据,比如:30分钟前展示“x分钟前“,半小时到1小时展示“半小时前”,1小时到一天展示“x小时前”,一天以后展示“x天前”
根据差距,比对符合的展示数据。
<script type="text/javascript">function formatStr( ){
var str = arguments[0]
var arr = [].splice.call(arguments,1,arguments.length -1)
return str.replace(/\{(\d+)\}/g,function(s,i){
if(arr[i]!='0'){
return arr[i] || ''
}else{
return arr[i]
}
})
}
function show( date ){
//date 是 js的日期对象
var now = +new Date()
var target = date.getTime()
var diff = now - target//差距
var showArr = [
{
txt : '{0}分钟前',
times : 60 * 1000,
num : 30 * 60 * 1000
},
{
txt : '半小时前',
times : 60 * 1000,
num : 60 * 60 * 1000
},
{
txt : '{0}小时前',
times : 60 * 60 * 1000,
num : 24 * 60 * 60 * 1000
}
]
var txt = '{0}天前',num = 0,times = 24 * 60 * 60 * 1000
for(var i=0i<showArr.lengthi++){
var item = showArr[i]
if( diff < item.num){
txt = item.txt
times = item.times
break
}
}
var show = Math.floor(diff / times)
txt = formatStr(txt,show)
return txt
}
var targetDate = new Date('2018-03-10')
console.log(show(targetDate))
</script>
提供一个思路,自己尝试写代码.如果不会写再追问:先把自己想要的时间换算成秒=S,比如定位到一分钟前则为60秒,然后获取当前时间时间戳减去S,再将得出的结果转化为北京时间即可