Erlang操作时间

1、首先,说说时间相关的基础函数,类似于其它语言中的获取时间戳函数。

查下API文档,描述如下:

erlang:now() -> timestamp()

timestamp() {MegaSecs, Secs, MicroSecs}

MegaSecs Secs MicroSecs integer() >= 0

可以看到,这个就是erl中的获取时间戳的方法,知识她精确到了微妙。erl系统确保这个api的返回值不会重复,这个特性很厉害,据说pid创建就与这个为基础。

结果以tuple形式形式返回。Secs为秒的简写,Mega宏达的意思,Micro极小的意思,MegaSecs兆秒,MicroSecs微妙。

为了和其它语言方便通信,有时候需要转换成标准时间戳(UTC197011000秒起至现在的总秒数)Now转换成标准时间戳的方法。

now_to_s({MegaSecs,Secs,_})->

MegaSecs*1000000+Secs.


    2、获取日期时间的函数

date() -> Date

Date calendar:date()

Returns the current date as {Year, Month, Day}.

 

time() -> {Hour, Minute, Second}

Hour Minute Second integer() >= 0

Returns the current time as {Hour, Minute, Second}

 

标准函数中的datetime分别返回当地的日期时间,对应于calendar:local_time()

calendar:local_time()的返回值为{date(),time()}。标准函数中有datetime了,calendar

中为什么还要设计local_time呢。文档上描述是为了避免先调用time(),再调用date(),正好在隔日的分界点,就会出现问题了。

     

3erlang日期时间转换为时间戳的方法。

calendar:datetime_to_gregorian_seconds(DateTime) -> Seconds

DateTime datetime()

Seconds integer() >= 0

这个返回的是格林尼治标准时间秒数。

格林尼治标准时间(GMT),这个秒数是当前到0,,0,0 0,0,0

时间戳用的是utc时间。综上,方法如下:

calendar:datetime_to_gregorian_seconds(LocalDateTime)-calendar:datetime_to_gregorian_seconds({{1970,1,1},{8,0,0}}).

如果存储的不是本地时间,则:

calendar:datetime_to_gregorian_seconds(DateTime)-calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}}).




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值