Unix时间戳转化时间

因为项目中经常用到Unix时间戳的转化,今天就总结一下

PHP中
这种方式在PHP程序中完成转换,优点是无论是不是数据库中查询获得的数据都能转换,转换范围不受限制,缺点是占用PHP解析器的解析时间,速度相对慢。
用函数:
date() 一般形式:date(‘Y-m-d H:i:s’, unix时间)
PHP中将正常时间戳转化为Unix时间戳
用函数:echo strtotime(“now”), “\n”;
echo strtotime(“10 September 2000”), “\n”;
echo strtotime("+1 day"), “\n”;
echo strtotime("+1 week"), “\n”;
echo strtotime("+1 week 2 days 4 hours 2 seconds"), “\n”;
echo strtotime(“next Thursday”), “\n”;
echo strtotime(“last Monday”), “\n”;

MySQL中
这种方式在MySQL查询语句中转换,优点是不占用PHP解析器的解析时间,速度快,缺点是只能用在数据库查询中,有局限性。

  1. UNIX时间戳转换为日期用函数: FROM_UNIXTIME()
    一般形式:select FROM_UNIXTIME(1156219870);
  2. 日期转换为UNIX时间戳用函数: UNIX_TIMESTAMP()
    一般形式:Select UNIX_TIMESTAMP(‘2006-11-04 12:23:00′);
    举例:mysql查询当天的记录数:
    $sql=”select * from message Where DATE_FORMAT(FROM_UNIXTIME(chattime),’%Y-%m-%d’) = DATE_FORMAT(NOW(),’%Y-%m-%d’) order by id desc”;

JS中
UNIX时间戳转换为日期用函数
new Date(Unix时间戳*1000)
在这里插入图片描述
但是格式并不尽如人意,自定义format函数对其进行格式转化
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
Date.prototype.Format = function(fmt)
{ //author: meizz
var o = {
“M+” : this.getMonth()+1, //月份
“d+” : this.getDate(), //日
“h+” : this.getHours(), //小时
“m+” : this.getMinutes(), //分
“s+” : this.getSeconds(), //秒
“q+” : Math.floor((this.getMonth()+3)/3), //季度
“S” : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : ((“00”+ o[k]).substr((""+ o[k]).length)));
return fmt;
}

new Date(Unix时间戳*1000).Format(“yyyy-MM-dd hh:mm:ss”);
在这里插入图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值