4
$\begingroup$

Question 1

DateObject["30.08.90"] returns Day: Mon 2 Jun 1997. How do I get DateObject["06.02.97"] to return Day: 6 Feb 1997 rather than Day: Mon 2 Jun 1997?

Question 2

How can I convert a list of date strings into a list of date objects that can then be sorted?

$\endgroup$
7
$\begingroup$

Use the the syntax where you specify the order:

DateObject[{"06.02.97",{"Day","Month","YearShort"}}]

DateObject[{1997, 2, 6, 0, 0, 0.}, "Instant", "Gregorian", -7.]

$\endgroup$
  • $\begingroup$ Since, as far as I can tell, this option isn't in the DateObject documentation, but rather in the DateList doc, is this essentially just a shortcut for DateObject@DateList[{"06.02.97",{"Day","Month","YearShort"}}]? $\endgroup$ – That Gravity Guy Oct 4 at 7:20
  • $\begingroup$ @ThatGravityGuy It is in the documentation starting in M11. What version do you have? $\endgroup$ – Carl Woll Oct 4 at 8:34
  • $\begingroup$ Ah, well there's my problem. I work with 10.1.0 and should remember to check the up-to-date online docs. I was working heavily with 8.0 for about 5 years up until a few months ago. $\endgroup$ – That Gravity Guy Oct 4 at 8:39
4
$\begingroup$

Since I couldn't find the elegant solution @Carl Woll did, how about this?

Quiet@DateObject@StringReplace[
 "06.02.97",
 day__ ~~ "." ~~ mon__ ~~ "." ~~ yr__ :> mon <> "." <> day <> "." <> yr
]

DateObject[{1997, 2, 6}]

It does throw the warning

DateObject::ambig: "Warning: the interpretation of the string 02.06.97 as a date is ambiguous."

but since you know this is what you want, then you can use the Quiet.

As for your second question, in general you could do

DateObject /@ listofdatestrings

but if all of the date strings are in the day.month.year format as above, then you could use

DateObject /@ StringReplace[
 listofdatestrings,
 day__ ~~ "." ~~ mon__ ~~ "." ~~ yr__ :> mon <> "." <> day <> "." <> yr
] // Quiet

For example

DateObject /@ StringReplace[
 {"06.02.97", "30.08.90"}, 
 day__ ~~ "." ~~ mon__ ~~ "." ~~ yr__ :> mon <> "." <> day <> "." <> yr
] // Quiet

{DateObject[{1997, 2, 6}], DateObject[{1990, 8, 30}]}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.