Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I round to a week #3063

Open
lucacasonato opened this issue Dec 11, 2024 · 1 comment
Open

How do I round to a week #3063

lucacasonato opened this issue Dec 11, 2024 · 1 comment
Labels

Comments

@lucacasonato
Copy link
Member

Given a random Temporal.ZonedDateTime, I would like to get a Temporal.ZonedDateTime for the time 00:00:00.000000 of the first Monday before that time. I have tried:

  • round(): does not support week as a rounding mode
  • Temporal.ZonedDateTime.from({
      timeZone: dateTime.timeZoneId,
      year: dateTime.year,
      weekOfYear: dateTime.weekOfYear,
      dayOfWeek: 1,
    });
  • with(): does not support as an argument dayOfWeek

Is the only way to do this to manually by subtracting dayOfWeek from itself? Ie:

dateTime
  .round({ smallestUnit: "day", roundingMode: "trunc" })
  .subtract({ days: dateTime.dayOfWeek - 1 });
@ptomato
Copy link
Collaborator

ptomato commented Feb 14, 2025

Sorry the answer took so long; I lost this in my holiday notifications pile-up.

tl;dr, yes, subtracting dayOfWeek is the way to do it. You could make that code slightly smaller by using startOfDay() to truncate to midnight: dateTime.startOfDay().subtract(...) or if you just need the date and not the midnight, preferably toPlainDate(). See also https://tc39.es/proposal-temporal/docs/cookbook.html#nth-weekday-of-the-month for some similar recipes.

More background on why this is not supported by ZonedDateTime.p.round() is discussed in #1785. Unlike rounding a Duration, when you round a ZonedDateTime you are actually 'snapping' to the nearest start of a time unit. 'Start of a day' or 'start of a minute' are well-defined but 'start of a week' is not. We could choose to make it well-defined in the future, so there's a Temporal V2 issue open for exploring it: js-temporal/proposal-temporal-v2#20

The from() and with() ideas don't work because we don't support yearOfWeek/weekOfYear/dayOfWeek as a first-class scheme to create or manipulate dates. There's no reason why we couldn't, just that it didn't make the cut for V1. Here's the Temporal V2 issue for it, if you want to follow it: js-temporal/proposal-temporal-v2#11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants