希望能幫助別人。
如果有人指出有什麼可以改進的地方,請多多指教。提前致謝!
port_helper.erl
-module(port_helper).
-export([get_stdout/1]).
get_stdout(Port) ->
loop(Port, []).
loop(Port, DataAcc) ->
receive
{Port, {data, Data}} ->
loop(Port, DataAcC++ Data);
{Port, eof} ->
DataAcc
end.
timestamp_with_time_zone.erl
-module(timestamp_with_time_zone).
-export([to_time_zone/2, to_universal_time/1, modify/2]).
to_time_zone({{{Year, Month, Day}, {Hour, Minute, Second}}, TimeZone}, OutputTimeZone) ->
InputPattern = "~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B",
InputDeep = io_lib:format(InputPattern, [Year, Month, Day, Hour, Minute, Second]),
Input = lists:flatten(InputDeep),
{external_date(Input, TimeZone, OutputTimeZone), OutputTimeZone}.
to_universal_time({{{Year, Month, Day}, {Hour, Minute, Second}}, TimeZone}) ->
{Timestamp, "UTC"} = to_time_zone({{{Year, Month, Day}, {Hour, Minute, Second}}, TimeZone}, "UTC"),
Timestamp.
modify({{{Year, Month, Day}, {Hour, Minute, Second}}, TimeZone}, {Times, Unit}) ->
if
Times > 0 ->
TimesModifier = "";
Times < 0 ->
TimesModifier = " ago"
end,
InputPattern = "~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B ~.10B ~s~s",
InputDeep = io_lib:format(InputPattern, [Year, Month, Day, Hour, Minute, Second, abs(Times), Unit, TimesModifier]),
Input = lists:flatten(InputDeep),
external_date(Input, TimeZone, TimeZone).
external_date(Input, InputTimeZone, OutputTimeZone) ->
CmdPattern = "date --date 'TZ=\"~s\" ~s' +%Y%m%d%H%M%S",
CmdDeep = io_lib:format(CmdPattern, [InputTimeZone, Input]),
Cmd = lists:flatten(CmdDeep),
Port = open_port({spawn, Cmd}, [{env, [{"TZ", OutputTimeZone}]}, eof, stderr_to_stdout]),
ResultString = port_helper:get_stdout(Port),
case io_lib:fread("~4d~2d~2d~2d~2d~2d", ResultString) of
{ok, [YearNew, MonthNew, DayNew, HourNew, MinuteNew, SecondNew], _LeftOverChars} ->
{{YearNew, MonthNew, DayNew}, {HourNew, MinuteNew, SecondNew}}
end.
不明白爲什麼你不能戳轉換爲UTC,然後向CET - 你只需要正確地做到這一點。我不知道Erlang的模塊,但你可以嘗試用[TZ數據庫](http://www.twinsun.com/tz/tz-link.htm)自己實現它。 – hdima 2011-03-29 07:47:55
問題在於「正確執行」。爲了從一個時區轉換到另一個時區或者對時區進行算術運算,人們需要知道兩個時區的偏移量和DST特徵,這就是問題本身。即使有了這些知識,實施也不是那麼簡單。 – trytrytry 2011-03-29 08:36:02
I. e。 「從零開始實施一切」是可以實現的,但與解析linux date util result IMHO相比,利潤並不包括複雜性。 – trytrytry 2011-03-29 08:38:28