时间戳时期格式化
2016/06/13 标签:
javascript
时间戳格式化
parseTime()
/**
* 格式化日期
* @param timesamp 数据库时间戳
* @param format 如y-m-d h:i:s
* @param full 是否补零 5 => 05
* @returns {string}
*/
function parseTime(timestamp,format,full){
full = full != undefined ? full : true;
timestamp = timestamp * 1000;
if(!format) format="y-m-d h:i:s";
format = format.toLowerCase();
function zeroFull(str){
return full ? (str >=10 ? str : ('0' + str)):str;
}
var time=new Date(timestamp);
o = {
y : time.getFullYear(),
m : zeroFull(time.getMonth()+1),
d : zeroFull(time.getDate()),
h : zeroFull(time.getHours()),
i : zeroFull(time.getMinutes()),
s : zeroFull(time.getSeconds())
}
return format.replace(/([a-z])(1)*/ig,function(m){
return o[m];
});
}
console.log(parseTime(1451460186,"y年m月d日 h:i"));
//2015年12月30日 15:23
console.log(parseTime(1451460189,"y-m-d h:i"));
//2015-12-30 15:23
console.log(parseTime(1451460189,"m-d h:i"));
//12-30 15:23
console.log(parseTime(1451460189,"h:i"));
//15:232.timeAgo()
/**
* 多久之前
* @param stamp 数据库时间戳
* @param format 对于不在范围的日期格式化 如 y-m-d h:i:s
* @param max 最大级别 默认 月
* @returns {string}
*/
function timeAgo(stamp,format,max){
max = max ? parseInt(max) : 2592000;
var now = (new Date() * 1) / 1000,
time = now - stamp,
text = {
31536000 : '年',
2592000 : '个月',
604800 : '周',
86400 : '天',
3600 : '小时',
60 : '分钟',
1 : '秒'
};
var back = '';
if(time <= max){
for(var k in text){
var c = Math.floor(time / parseInt(k));
if( 0 != c){
if(text[k] == '天' && c <= 2){
back = (((c == 1) ? "昨天" : "前天")+parseTime(stamp,'h:i'));
}else{
back = (c + text[k] + "前");
}
}
}
}else{
back = parseTime(stamp,format);
}
return back;
}
console.log(timeAgo(1451460186,"m-d h:i"));
//3小时前转自:http://www.smohan.net/blog/5043/
静水缘首页
文章分类
最新文章
- nodejs私钥加密公钥解密的一个例子
- uniapp和微信小程序判断程序运行在开发或者测试或者线上版本的方法分别是什么
- electron使用electron-builder打包后模块包含exe文件执行失败
- Compile is disallowed on the main thread, if the buffer size is larger than 4KB
- better-sqlite3简介及常用操作
- nodejs 操作数据库的库
- nodejs使用http-proxy库实现多个域名代理和同时代理websocket的例子,代理包含https和http两种协议
- iis配置反向代理
- javascript伪多线程代码
- ip所在地址段判断