I have a number representing date (yyyymmdd):
19001231
I want to convert this number to
{1900,12,31}
How to do this? There should be easy answer.
You can also use NumberDecompose
with the basis {10000, 100, 1}
:
NumberDecompose[19001231, 10^{4, 2, 0}]
{1900, 12, 31}
NumberDecompose
$\endgroup$
DateList[{IntegerString @ #, {"Year", "", "Month", "", "Day"}}][[;; 3]] & @ 19001231
{1900, 12, 31}
DateObject[{IntegerString@#, {"Year", "", "Month", "", "Day"}}] & @ 19001231
Since the year is fixed 4 digits, and day and month are fixed 2 digits, one way is to do
n=19001231;
m=IntegerDigits[n];
FromDigits[#]&/@{m[[1;;4]],m[[5;;6]],m[[7;;8]]}
There might be a build in function that does this already related to date/time formatting. I have not looked.
FromDigits /@ {m[[;; 4]], m[[5 ;; 6]], m[[7 ;;]]}
$\endgroup$
Commented
Feb 14, 2022 at 3:41
Yet another one-liner: FoldPairList
+ QuotientRemainder
:
FoldPairList[QuotientRemainder, 19001231, 10^{4, 2, 0}]
{1900, 12, 31}
Interpret the string as a "Date".
Interpreter["Date"]["19001231"][#] & /@ {"Year", "Month", "Day"}
{1900, 12, 31}
EDIT
I should have said: convert the number to string; interpret the string as a date and then extract parts (to answer the question as posed and also to avoid repeating the caculations).
str = IntegerString@19001112
dobj = Interpreter["Date"][str]
{y, m, d} = dobj[#] & /@ {"Year", "Month", "Day"}
Interpreter
is slow, but it is a built-in function designed for the purpose.
f[#]&/@ ...
could be written as f/@...
$\endgroup$
Commented
Feb 14, 2022 at 17:31
Processing dates by integers is extremely error-prone. Here is an example from the excellent book by Paul Wellin (p.598).
Compare this
DateList[19001231];
Take[%,3]
(* Out: {1900, 8, 8} *)
with this
DateList[ToString[19001231]]
Take[%, 3]
(* Out: {1900, 12, 31} *)
Similar to the response by @Nasser
MapAt[FromDigits,
TakeList[IntegerDigits[19001231], {4, 2, 2}], {{1}, {2}, {3}}]
which yields
{1900, 12, 31}
FromDigits/@TakeList[IntegerDigits[19001231],{4,2,2}]
(which I was going to post!)
$\endgroup$
An option using the Date functionality:
DateValue[#, {"Year", "Month", "Day"}] &@DateObject@ToString@19001231
ToExpression @* StringJoin /@
TakeList[Characters @ ToString[19001231], {4, 2, 2}]
{1900, 12, 31}
Using DateString
and StringSplit
:
dstr = DateString[ToString@19001231, "ISODate"]
"1900-12-31"
ToExpression@StringSplit[dstr, Except[DigitCharacter]]
{1900, 12, 31}
The shortest form (Thanks to @eldo!):
StringSplit[DateString[19001231, "ISODate"], "-"]
StringSplit[DateString[19001231, "ISODate"], "-"]
$\endgroup$