5
$\begingroup$

I have a DateObject with lots of granularity and additional specifications, such as the following e.g.:

dateFull = 
 DateObject[
  List[2022, 7, 18, 14, 0, 0],
  "Instant", "Gregorian", 0, "SmearedUTC",   
  List["DateTime", ":", "Millisecond"]
 ]

I would like to find a function f such that f[dateFull] returns DateObject[List[2022, 7, 18], "Day"]. This makes comparing dates easier as I can use functions such as Complement, DeleteDuplicates etc. when I am only concerned with the "Day" granularity.

In v13 I used to do this with DateObject[dateFull, "Day"] (see also DateObject granularity conversion), but in v13.1 it now returns the CalendarType ("Gregorian") as well i.e.: DateObject[List[2022, 7, 18], "Day", "Gregorian", 0].

Doing something like f = DateObject[DateString[#, {"ISODate"}], "Day"]& would work, but it feels ugly/hacky as it seems to imply that I would be better off working with Strings instead of DateObjects. (Indeed, given the ever evolving output of DateObject that may well be the case: if memory serves, DateObject[x, "Day"] behaviour was also different in v12. It seems like Wolfram is not quite happy with their dates behaviour.)

$\endgroup$
2
  • 2
    $\begingroup$ Is the "Gregorian", 0 bit breaking any code? You can do something like DateObject[dateFull, "Day"][[;; 2]] which works in v12 through 13.1 from what I can tell $\endgroup$
    – Jason B.
    Commented Aug 2, 2022 at 11:52
  • 1
    $\begingroup$ @Jason.B yes sadly it is causing breaks. eg. Complement[ { DateObject[List[2022,7,18],"Day"], DateObject[List[2022,7,19],"Day"] }, {DateObject[List[2022,7,18],"Day","Gregorian",0.`]} ] Thanks I will try DateObject[dateFull, "Day"][[;; 2]] $\endgroup$ Commented Aug 2, 2022 at 12:11

1 Answer 1

5
$\begingroup$

I got in touch with the Wolfram technical team about this and they have suggested :

timeZoneApproach=DateObject[#, "Day", TimeZone -> None]&;

FullForm[timeZoneApproach[dateFull]] (* DateObject[List[2022,7,18],"Day"] *)

The suggestion from @Jason.B is about 2 times faster on my machine, but you run the risk that the DateObject function might return the position of List and "Day" differently in future upgrades.

For completeness:

partApproach = DateObject[#, "Day"][[;; 2]] &;

pA = partApproach[dateFull]; // RepeatedTiming (*{0.0000198191,Null}*)
tZ = timeZoneApproach[dateFull]; // RepeatedTiming (*{0.0000387157,Null}*)

pA === tZ (*True*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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