I have some saved dates in JavaScript using new Date()
that looks like:
"Sun Feb 24 2019 14:44:20 GMT+0200 (Eastern European Standard Time)"
I'm trying to parse these to Elixir DateTime
; I didn't find anything in "timex" that can help and I already know that I can use DateTime.from_iso8601
but for dates saved using new Date().toISOString()
but what i need is to parse the above string.
Thanks in advance
You can use elixir binary pattern matching to extract the date parts and parse using Timex's RFC1123
format. The RFC1123 is the format eg Tue, 05 Mar 2013 23:25:19 +0200
. Run h Timex.Format.DateTime.Formatters.Default
in iex to see other formats.
iex> date_string = "Sun Feb 24 2019 14:44:20 GMT+0200 (Eastern European Standard Time)"
iex> <<day_name::binary-3,_,month_name::binary-3,_,day::binary-2,_,year::binary-4,_,time::binary-8,_::binary-4,offset::binary-5,_,rest::binary>> = date_string
iex> Timex.parse("#{day_name}, #{day} #{month_name} #{year} #{time} #{offset}", "{RFC1123}")
iex> {:ok, #DateTime<2019-02-24 14:44:20+02:00 +02 Etc/GMT-2>}
Pattern matching: The binary-size are in byte sizes. 1 byte == 1 character. For instance to get 3-character day_name
the size is 3. Underscores (_) is used to pattern match the spaces in the date format
Updated answer to use binary-size
rather than bitstring-size for simplicity
I didn't find anything in "timex" that can help
The Timex Parsing docs say that you can use strftime
sequences, eg %H:%M:%S
, for parsing. Here's a list of strftime characters and what they match.
Here's a format string that I think should work on javascript Dates:
def parse_js_date() do
Timex.parse!("Sun Feb 24 2019 14:44:20 GMT+0200 (Eastern European Standard Time)",
"%a %b %d %Y %H:%M:%S GMT%z (%Z)",
:strftime)
end
Unfortunately, %Z
doesn't want to match the time zone name, which causes Timex.parse!()
to spit out an error. It looks like %Z
in Elixir only matches one word, eg a timezone abbreviation EET
. Therefore, my simple, clean solution is spoiled.
What you can do is chop off the time zone name before parsing the date string:
def parse_js_date_string() do
[date_str|_tz_name] = String.split(
"Sun Feb 24 2019 14:44:20 GMT+0200 (Eastern European Standard Time)",
" (",
parts: 2
)
Timex.parse!(date_str,
"%a %b %d %Y %H:%M:%S GMT%z",
:strftime)
end
In iex:
~/elixir_programs/my$ iex -S mix
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Compiling 1 file (.ex)
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> My.parse_js_date_string()
#DateTime<2019-02-24 14:44:20+02:00 +02 Etc/GMT-2>
iex(2)>
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.