Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bucklescript: get week number of year
/* For a given date, get the ISO week number
*
* This is copied from
* https://stackoverflow.com/a/6117889/5550386
*
* ... which is based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest Thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
let getWeekNumber = (date: Js.Date.t) => {
open Js.Date;
/* Copy date so don't modify original */
let date = date |> getTime |> fromFloat;
/* Set to nearest Thursday: current date + 4 - current day number
Make Sunday's day number 7 */
let date =
setUTCDate(date, getUTCDate(date) +. 4.0 -. getUTCDay(date))
|> fromFloat;
/* Get first day of year */
let yearStart =
fromFloat(
utcWithYMD(~year=getUTCFullYear(date), ~month=0., ~date=1., ()),
);
let milliSecondsInADay = 86400000.0;
/* Calculate full weeks to nearest Thursday */
let weekNumber =
ceil(
((getTime(date) -. getTime(yearStart)) /. milliSecondsInADay +. 1.)
/. 7.,
);
weekNumber;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment