Erlang 日期和时间处理、时间戳转换

本文详细介绍了Erlang编程语言中now()和timestamp()函数的区别,以及如何进行时间戳与时间之间的转换。重点在于理解两者在获取操作系统时间时的差异,并提供了一种简便的方法将时间转换为时间戳和从时间戳转换回时间。

http://www.csdn 123.com/html/blogs/20131113/95993.htm

获取当前时间

erlang:now()得到的是从1970年1月1日零时起,到现在经过的时间,结果为{MegaSecs, Secs, MicroSecs}。有个问题要注意,还有另外一个函数可以实现同样的功能:os:timestamp()

那么erlang:now()和os:timestamp()的区别是什么?

erlang的解释如下:

erlang:now()

If you do not need the return value to be unique and monotonically increasing, use os:timestamp/0 instead to avoid some overhead.

os:timestamp()

The difference is that this function returns what the operating system thinks (a.k.a. the wall clock time) without any attempts at time correction. The result of two different calls to this function is not guaranteed to be different.

大致的意思是:erlang:timestamp()获取到的时间更接近于操作系统时间,erlang:now()每次获取都会生成唯一的时间,看来erlang:now()在实现上对时间多做了一个校正,相对erlang:timestamp()有点失真,同时也会有多余的开销。但是erlang:now()每次都生成唯一的值,有时候对我们来说也是一大利好的

获取当前时间戳

 

timestamp() ->
    {M, S, _} = os:timestamp(),
    M * 1000000 + S.

获取当前时间

 

 

% 本地时间
local_time() ->
    calendar:local_time().

% 世界时间
world_time() ->
    calendar:universal_time().

获取年月日,时分秒

 

1> {{Year, Month, Day}, {Hour, Minite, Second}} = calendar:local_time().
{{2013,11,13},{20,10,10}}
2> Day.
13
3> Second.
10

时间转换

 

% 秒转时间
11> calendar:seconds_to_daystime(86000).
{0,{23,53,20}}
12> calendar:seconds_to_daystime(86400).
{1,{0,0,0}}
13> calendar:seconds_to_daystime(1086400).
{12,{13,46,40}}

% 时间转秒
14> calendar:time_to_seconds({23,53,20}).
86000

 

时间与时间戳的转换

 

% 时间转时间戳,格式:{{2013,11,13}, {18,0,0}}
datetime_to_timestamp(DateTime) ->
    calendar:datetime_to_gregorian_seconds(DateTime) -
       calendar:datetime_to_gregorian_seconds({{1970,1,1}, {0,0,0}}).

% 时间戳转时间
timestamp_to_datetime(Timestamp) ->
    calendar:gregorian_seconds_to_datetime(Timestamp +
      calendar:datetime_to_gregorian_seconds({{1970,1,1}, {0,0,0}})).

时间格式化

 

-module(print_time).
-export([format_utc_timestamp/0]).
format_utc_timestamp() ->
    TS = {_,_,Micro} = os:timestamp(),
    {{Year,Month,Day},{Hour,Minute,Second}} = 
	calendar:now_to_universal_time(TS),
    Mstr = element(Month,{"Jan","Feb","Mar","Apr","May","Jun","Jul",
			  "Aug","Sep","Oct","Nov","Dec"}),
    io_lib:format("~2w ~s ~4w ~2w:~2..0w:~2..0w.~6..0w",
		  [Day,Mstr,Year,Hour,Minute,Second,Micro]).

编译这个模式,运行如下:

 

 

1> io:format("~s~n",[print_time:format_utc_timestamp()]).
29 Apr 2009  9:55:30.051711

转载于:https://www.cnblogs.com/fvsfvs123/p/4275724.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值