Bob Haslett
Bob Haslett

Reputation: 1103

Check to see if a year is a century

Working on some conditional formatting in d3 and need to check if a date is the turn of a century or not. eg 1945 and 1998 are not, 1900 and 2000 are. Not sure how to go about it, perhaps checking to see if getting the full year and dividing by a 100 is an integer, but that seems a little non specific to me. Any help appreciated.

interval is the string passed to the function that denotes if the tick are ever month, year decade etc. I'd like to check if a date is a decade at the if (fulYear) condition, so its if fullYear or date is a century

function tickFormat(interval) {
        return {
            "decade":d3.timeFormat("%y"),
            "lustrum":d3.timeFormat("%y"),
            "years":function(d) {
                if (fullYear) {
                    format=d3.timeFormat("%Y")
                    return format(d)
                }
                else {
                    format=d3.timeFormat("%y");
                    return format(d)
                }
            },
            "quarters":d3.timeFormat("%b"),
            "months":d3.timeFormat("%b"),
            "weeks":d3.timeFormat("%b"),
            "days":d3.timeFormat("%d"),
            "hours":d3.timeFormat("%I"+":00")
        }[interval]
    }

Upvotes: 2

Views: 1091

Answers (1)

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Use the reminder operator - %. This returns the reminder of the division, if it's 0 then it's a century.

if ( 1900 % 100 === 0) { //do your job }

This way you don't need to check whether 1900 / 100 is an integer.

Upvotes: 5

Related Questions