5
$\begingroup$

The entities representing the days of the week sort alphabetically:

Sort[{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}]

(* {Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday} *)

(Note that these are not strings.)

Is there a better way to sort than using the following?

SortBy[PositionIndex[{Monday, Tuesday, Wednesday, Thursday, Friday}]]
$\endgroup$
  • $\begingroup$ Wouldn't this be ill-defined because it is cyclic? I guess you could order them if you agree on which day is the first of the week… some say monday, others sunday… $\endgroup$ – SHuisman Sep 19 at 11:28
  • $\begingroup$ "Canonically" (i.e. according to the Bible) the first day was Sunday. $\endgroup$ – mikado Sep 19 at 20:43
  • $\begingroup$ I don't know if you can get more canonical than the Bible, but according to ISO 8601, the week begins on Monday. $\endgroup$ – Stephen Powell Sep 20 at 7:30
4
$\begingroup$

It is not much shorter than your PositionIndex[{Monday, Tuesday, Wednesday, Thursday, Friday}], but you can also use System`DateObjectDump`$dowAssociation:

System`DateObjectDump`$dowAssociation

<|Monday -> 1, Tuesday -> 2, Wednesday -> 3, Thursday -> 4, Friday -> 5, Saturday -> 6, Sunday -> 7|>

sortByDoW = SortBy[System`DateObjectDump`$dowAssociation];

Examples:

sortByDoW @ {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

sortByDoW @ RandomSample[{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}]

{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

$\endgroup$
2
$\begingroup$

As you've noticed, the weekday symbols are by default sorted by their symbol names. This is because Monday,... are not true date specifications, but only day types. So there is not really a canonical ordering. However, you could do the following:

SortBy[DayPlus[DayPlus[Today, 1, Sunday], 1, #] &]@
  {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
(* {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} *)

This works by converting the day types into actual dates. This is done in three steps:

  • Find the next Sunday after today (you could also hardcode the date of a sunday here, but this is more readable I think)
  • Find the date of the first Monday/... after that point
  • Sort these dates
$\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.