简体   繁体   中英

Elixir: Local System Date Format

Is it possible to find out the date format the machine is using in Elixir? ie dd/mm/yy or mm/dd/yy so we can format a date string accordingly?

You can use DateTime.utc_now and then format date you want:

iex(5)> d = DateTime.utc_now  
#DateTime<2019-05-16 15:01:51.662814Z>
iex(6)> DateTime.to_string(d)
"2019-05-16 15:01:51.662814Z"
iex(7)> s = "#{d.year}/#{d.month}/#{d.day}"
"2019/5/16"

Or you can get the data format from :calendar.local_time like below and then print it into everything you want:

iex(12)> {{y, m, d},_} =  :calendar.local_time()
{{2019, 5, 16}, {22, 4, 29}}
iex(13)> y
2019
iex(14)> m
5
iex(15)> d
16

In "core Elixir" there is no such functionality, as Elixir/Erlang do not ship with locales data nor it provides API to use system data. Instead you need to fetch CLDR data on your own and use that, fortunately there is ex_cldr library that does that for you. In addition there is extension ex_cldr_date_times that supports formatting dates. So in the end, when you install both of these libraries you can use:

Cldr.DateTime.to_string(DateTime.utc_now)

To receive localized string in current locale.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM