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

Round to nearest X of interval #787

Closed
LandonSchropp opened this issue Jun 20, 2018 · 4 comments
Closed

Round to nearest X of interval #787

LandonSchropp opened this issue Jun 20, 2018 · 4 comments

Comments

@LandonSchropp
Copy link

Sorry if this has already been answered, but I searched the issues and docs and didn't see anything like this.

Is there a way to round to the nearest X of an interval with date-fns? For example, is there anything like this?

roundToNearestMinute(new Date())
roundToNearestMinutes(new Date(), 5)
roundToNearest(new Date(), 5, "minutes")

startOfMinutes(new Date(), 5)
startOf(new Date(), 5, "minutes")

endOfMinutes(new Date(), 5)
endOf(new Date(), 5, "minutes")
@vgebrev
Copy link

vgebrev commented Jul 18, 2018

This works for me to round minutes (not a general solution, feel free to expand, my use case was to just round down to the start of nearest 15min):

function roundToNearestMinutes(date, interval) {
    var roundedMinutes = Math.floor(getMinutes(date) / interval) * interval;
    return setMinutes(startOfMinute(date), roundedMinutes); 
}

// usage: round to nearest 15min
console.log(roundToNearestMinutes(new Date(2018, 7, 1, 8, 32, 42, 69), 15)); 
// 2018-Aug-01 08:30:00.000

@kossnocorp
Copy link
Member

I like the idea. 👍 for roundToNearestMinutes

@xkizer
Copy link
Contributor

xkizer commented Oct 13, 2018

#928

@kossnocorp
Copy link
Member

This functionality was released as v2.0.0-alpha.23. See the change log: https://gist.github.com/kossnocorp/a307a464760b405bb78ef5020a4ab136#v200-alpha23

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

No branches or pull requests

4 participants