问题
I need to generate a string with the current time in the same format as the following: 20130524T000000Z
The example is a timestamp for Fri, 24 May 2013 00:00:00 GMT
.
How would I do that? Is there a way to do it without external packages?
回答1:
Updated 2016-07-18
Elixir 1.3 and up has support for this natively:
iex> DateTime.utc_now() |> DateTime.to_iso8601()
"2016-07-18T21:49:08.132428Z"
Original 2015-12-01 (with version differences added 2016-07-18, thanks @sebastian_k)
You could use the excellent timex library if you didn't mind using an external library:
timex 1.x (docs)
iex> Timex.Date.local |> Timex.DateFormat.format("{ISOz}")
{:ok, "2015-12-01T09:40:44.716Z"}
timex 2.x (docs)
iex> Timex.DateTime.local() |> Timex.format("{ISOz}")
{:ok, "2015-12-01T09:40:44.716Z"}
timex 3.x (docs)
iex> Timex.now() |> Timex.format("{ISO:Extended:Z}")
{:ok, "2015-12-01T09:40:44.716417ZZ"}
回答2:
I've managed to do with the following code:
{{yy, mm, dd}, {hh, mi, ss}} = :calendar.universal_time
"~.4.0w~.2.0w~.2.0wT~.2.0w~.2.0w~.2.0wZ"
|> :io_lib.format([yy, mm, dd, hh, mi, ss])
|> IO.iodata_to_binary
but perhaps there is a better way?
来源:https://stackoverflow.com/questions/34016207/how-to-generate-current-date-in-iso-8601-format-in-elixir