JSFiddle - React, Tailwind, and code Playground

by alnitak

JavaScript

function beginningOf(period, date) {
    date = new Date(date.valueOf()); // copy date

    if (period === "year" || period == "quarter") {
        date.setMonth(period === "quarter"
                      ? 3 * Math.floor(date.getMonth() / 3)
                      : 0);
        period = "month"; // now round down to the start of this month
    }

    if (period === "month" || period === "week") {
        date.setDate(period === "week"
                     ? date.getDate() - date.getDay()
                     : 1);
        period = "day"; // now round dow to the start of this day
    }
   
    // intentional switch fall-through
    switch (period) {
        case "day":
            date.setHours(0);
        case "hour":
            date.setMinutes(0);
        case "minute":
            date.setSeconds(0);
            date.setMilliseconds(0);
    }

    return date;
}

$(document.body).append(beginningOf("week", new Date("2014-04-03 22:17:10")));