//时间戳转换时间
function toDate(number){
var n=number; //注释 10位的 需要 乘以 1000,如(number * 1000) 13位就不需要
var date = new Date(n);
var Y = date.getFullYear() + '/';
var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
return (Y+M+D)
//var
h = date.getHours() +
':'
;
//
var
m = date.getMinutes() +
':'
;
//
var
s = date.getSeconds();
//
return
Y+M+D+h+m+s; 时分秒 更具自己需求
}
//将日期格式转换成时间戳:
var
date =
new
Date(
'2014-04-23 18:55:49:123'
);
// 有三种方式获取
var
time1 = date.getTime();
var
time2 = date.valueOf();
var
time3 = Date.parse(date);
console.log(time1);
//1398250549123
console.log(time2);
//1398250549123
console.log(time3);
//1398250549000
以上三种获取方式的区别:
第一、第二种:会精确到毫秒
第三种:只能精确到秒,毫秒用000替代
以上三个输出结果可观察其区别
注意:获取到的时间戳除以1000就可获得Unix时间戳,就可传值给后台得到。
=======================================================================
年龄计算:
假设出身年月 let old = '1993-10-10'
let oldage = old.substr(0, 4); //截取字符串从第0位开始截取4位 1993
获取当前时间戳:let new = Date.parse(new Date())
用上面的函数toDate转化:
时间戳转 日期: let newage = toDate(new) //2019
let age = newage - oldage // 26=
=====================================================
发布多久 的demo: 刚刚, 一小时前, 一个月前 等等
function getDateDiff(dateTimeStamp) {
var result;
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;
var now = new Date();//有些特殊 不能使用 new Date()
var diffValue = now - dateTimeStamp;
if (diffValue < 0) { return; }
var monthC = diffValue / month;
var weekC = diffValue / (7 * day);
var dayC = diffValue / day;
var hourC = diffValue / hour;
var minC = diffValue / minute;
if (monthC >= 1) {
result = "" + parseInt(monthC) + "月前";
}
else if (weekC >= 1) {
result = "" + parseInt(weekC) + "周前";
}
else if (dayC >= 1) {
result = "" + parseInt(dayC) + "天前";
}
else if (hourC >= 1) {
result = "" + parseInt(hourC) + "小时前";
}
else if (minC >= 1) {
result = "" + parseInt(minC) + "分钟前";
} else
result = "刚刚";
return result;
};
---------------------
案例:::::
效果图:
谢谢!!!!