electic
DateTime Format to string?
Hi,
I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to format a datetime to a string. Can someone point me in the right direction?
Most Liked
sztosz
You can do that
iex(1)> d = DateTime.utc_now
%DateTime{calendar: Calendar.ISO, day: 18, hour: 6, microsecond: {876000, 6},
minute: 8, month: 9, second: 59, std_offset: 0, time_zone: "Etc/UTC",
utc_offset: 0, year: 2016, zone_abbr: "UTC"}
iex(2)> DateTime.to_string(d)
"2016-09-18 06:08:59.876000Z"
iex(3)> s = "#{d.year}/#{d.month}/#{d.day}"
"2016/9/18"
LostKobrakai
There‘s also a standalone strftime implemention:
https://github.com/plataformatec/nimble_strftime
Most things calendar did found it‘s way into elixir core in the last few versions, so I tend to suggest it (as well as timex) less and less.
kujua
Edited to clarify:
Another way is - using this Calendar library:
iex(1)> nbo = Calendar.DateTime.now! "Africa/Nairobi"
%DateTime{calendar: Calendar.ISO, day: 23, hour: 12, microsecond: {149378, 6},
minute: 31, month: 7, second: 54, std_offset: 0, time_zone: "Africa/Nairobi",
utc_offset: 10800, year: 2016, zone_abbr: "EAT"}
iex(2)> nbo |> Calendar.DateTime.shift_zone!("Europe/Vienna")
|> Calendar.DateTime.Format.iso8601
"2016-07-23T11:31:54.149378+02:00"
First we create a timezone for Nairobi. The library uses the names in this list, so we define Africa/Nairobi as timezone name.
On the line iex(2) is the command to get the current date and time formatted as universal date time. We convert this into the Europe/Vienna timezoneand then we format the date and time to ISO 8601. There are more than 20 formats to choose from and if this is not covering your case it is possible to define custom formats.
The library must be loaded, for example by adding a dependency to mix.exs ({:calendar, “~> 0.16.0”}) and then run iex -S mix.
From my book Erlang and Elixir for Imperative Programmers, page 120.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









