Erlang - How Can I Parse RFC1123 Dates Into An Erl

2019-07-27 18:04发布

问题:

Without using a third party module, what steps would I need to take to convert this:

<<"Mon, 17 Feb 2014 11:07:53 GMT">>

Into this?:

[17, 2, 2014, 10, 07, 53]

Most of the answers I've Googled suggest using a library. So far, I suspect I'd get somewhere by pattern matching the formatted date string.

Something like:

<<_:5/binary, Date:2/binary>> = <<"Mon, 17 Feb 2014 11:07:53 GMT">>...

Which I think should produce the following 'match'

Date = 17...

That's based on an idea found here - https://groups.google.com/forum/#!topic/erlang-programming/OpXSqt3U86c - Is this a good approach?

Are there any BIF's or modules that can help with this? And furthermore, how would I convert/map "Feb" to an integer?

回答1:

Let's try that in the shell:

1> <<_:5/binary, Date:2/binary>> = <<"Mon, 17 Feb 2014 11:07:53 GMT">>.
** exception error: no match of right hand side value <<"Mon, 17 Feb 2014 11:07:53 GMT">>

Right, we need to match the rest of the binary at the same time:

2> <<_:5/binary, Date:2/binary, Rest/binary>> = <<"Mon, 17 Feb 2014 11:07:53 GMT">>.
<<"Mon, 17 Feb 2014 11:07:53 GMT">>
3> Date.
<<"17">>

So now Date is a binary containing the bytes for the ASCII digits 1 and 7. We can convert that to a number with binary_to_integer:

4> binary_to_integer(Date).
17

As for the conversion of month names to integers, the usual way to do something like that is with a function:

month_name_to_integer("Jan") -> 1;
month_name_to_integer("Feb") -> 2;
...
month_name_to_integer("Dec") -> 12.


回答2:

You may use tempo library for datetime formatting and parsing.



回答3:

Bin = <<"Mon, 17 Feb 2014 11:07:53 GMT">>,
L = binary_to_list(Bin),
{match, Res} = 
    re:run(L, "[0-9]+", [global, {capture, all, list}]),
[list_to_integer(X) || [X] <- Res].

the output is:

[17,2014,11,7,53]


回答4:

Why suffering? Why not third party module?

I am use erlware_commons

ec_date:parse("Mon, 17 Feb 2014 11:07:53 GMT").