Erlang操作时间

来源:互联网 发布:广州淘宝家具拍摄 编辑:程序博客网 时间:2024/06/05 17:35

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}}).




0 0
原创粉丝点击