好学IT学院:IT信息技术分享交流平台
来源:互联网  作者:本站整理  发布时间:2010-01-27  ★★★加入收藏〗〖手机版
摘要:一、MySQL 获得当前日期时间 函数1.1 获得当前日期+时间(date + time)函数:now()mysql select now();+-+| now() |+-……

五、MySQL 时间戳(Timestamp)函数

1. MySQL 获得当前时间戳函数:current_timestamp, current_timestamp()

mysql> select current_timestamp, current_timestamp();

+---------------------+---------------------+

current_timestamp

current_timestamp()


+---------------------+---------------------+

2009-08-09 23:22:24

2009-08-09 23:22:24


+---------------------+---------------------+

2. MySQL (Unix 时间戳、日期)转换函数:

unix_timestamp(),
unix_timestamp(date),
from_unixtime(unix_timestamp),
from_unixtime(unix_timestamp,format)

下面是示例:
select unix_timestamp(); -- 1218290027
select unix_timestamp('2009-08-08'); -- 1218124800
select unix_timestamp('2009-08-08 12:30:00'); -- 1218169800
select from_unixtime(1218290027); -- '2009-08-09 21:53:47'
select from_unixtime(1218124800); -- '2009-08-08 00:00:00'
select from_unixtime(1218169800); -- '2009-08-08 12:30:00'
select from_unixtime(1218169800, '%Y %D %M %h:%i:%s %x'); -- '2009 8th August 12:30:00 2009'

3. MySQL 时间戳(timestamp)转换、增、减函数:

timestamp(date) -- date to timestamp
timestamp(dt,time) -- dt + time
timestampadd(unit,interval,datetime_expr) --
timestampdiff(unit,datetime_expr1,datetime_expr2) --

请看示例部分:
select timestamp('2009-08-08'); -- 2009-08-08 00:00:00
select timestamp('2009-08-08 08:00:00', '01:01:01'); -- 2009-08-08 09:01:01
select timestamp('2009-08-08 08:00:00', '10 01:01:01'); -- 2009-08-18 09:01:01

select timestampadd(day, 1, '2009-08-08 08:00:00'); -- 2009-08-09 08:00:00
select date_add('2009-08-08 08:00:00', interval 1 day); -- 2009-08-09 08:00:00

MySQL timestampadd() 函数类似于 date_add()。
select timestampdiff(year,'2002-05-01','2001-01-01'); -- -1
select timestampdiff(day ,'2002-05-01','2001-01-01'); -- -485
select timestampdiff(hour,'2009-08-08 12:00:00','2009-08-08 00:00:00'); -- -12

select datediff('2009-08-08 12:00:00', '2009-08-01 00:00:00'); -- 7

MySQL timestampdiff() 函数就比 datediff() 功能强多了,datediff() 只能计算两个日期(date)之间相差的天数。

六、MySQL 时区(timezone)转换函数

convert_tz(dt,from_tz,to_tz)
select convert_tz('2009-08-08 12:00:00', '+08:00', '+00:00'); -- 2009-08-08 04:00:00

时区转换也可以通过 date_add, date_sub, timestampadd 来实现。
select date_add('2009-08-08 12:00:00', interval -8 hour); -- 2009-08-08 04:00:00
select date_sub('2009-08-08 12:00:00', interval 8 hour); -- 2009-08-08 04:00:00
select timestampadd(hour, -8, '2009-08-08 12:00:00'); -- 2009-08-08 04:00:00

小方法大作用:如何让网站PR值一路高歌
  做网站最痛苦的就是建站之初的那段时间,如长沙厂房出租网站刚建立,只是处于婴幼儿时期,没有流量、没有知名度、没有被百度收录、没有pr…
  • 好学考试H5触屏版开放内测
  • 好学触屏公众号虎力全开、杨帆起航!