amcdnl
amcdnl

Reputation: 8648

JavaScript set date to beginning of x

Im working on a fn that will set the date to the beginning of the minute/hour/day/week/month/quarter/year.

I've got a start with the week doing something like:

var date = new Date(),
    day = d.getDay(),
    // adjust when day is sunday
    diff = d.getDate() - day + (day == 0 ? -6 : 1);

    var updatedDate = new Date(date.setDate(diff);

but I have to wonder if there is a better way ( or framework ) to accomplish this type of thing?

Upvotes: 0

Views: 75

Answers (1)

Alnitak
Alnitak

Reputation: 340055

This is the best that I've been able to come up with so far:

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() // Sunday is the first day, adjust to suit
                     : 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;
}

See http://jsfiddle.net/alnitak/6hj9u/

It's a slightly harder problem than I had expected...

Upvotes: 1

Related Questions