How to convert day of week name to day of week number

前端 未结 3 1732
一生所求
一生所求 2021-01-23 00:03

How can I get the integer equivalent of days of the week i.e monday to 2, tuesday to 3, wednesday to 4

相关标签:
3条回答
  • 2021-01-23 00:32

    You could also use the "indexOf" function of javascript.

    var days  = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    
    console.log(days.indexOf('Sunday')); // return 0
    console.log(days.indexOf('Tuesday')); // return 2
    

    But remember that "indexOf" is case sensitive and that it will return "-1", if the string is not in the array.

    0 讨论(0)
  • 2021-01-23 00:42

    Can use a lookup object:

    var days = {
        sunday: 1,
        monday: 2,
        tuesday: 3,
        wednesday: 4,
        thursday: 5,
        friday: 6,
        saturday: 7
    }
    
    console.log(days["sunday"]) //1
    

    Now, simply access any of the above properties and it's value will be the numeric day of the week!

    console.log(days["monday"]) //2
    
    0 讨论(0)
  • 2021-01-23 00:43

    Typically, for something like this, you'll likely want to create a function so you don't have to repeat yourself (see DRY). Here's a sample function, that also converts the incoming week day string to lowercase so "Wednesday" will return the same result as "wednesday".

    Code (demo)

    Note: Comment block with function documentation is using style recommended by JSDoc.

    /**
     * @param {String} weekDay
     * @returns {Number} Day of week weekDay is. Returns `undefined` for invalid weekDay.
     */
    function getWeekDayNumber(weekDay) {
        var days = {
            sunday: 1,
            monday: 2,
            tuesday: 3,
            wednesday: 4,
            thursday: 5,
            friday: 6,
            saturday: 7
        };
    
        return days[weekDay.toLowerCase()];
    }
    
    var day = getWeekDayNumber("Sunday"); // `day` now equals `1`
    
    0 讨论(0)
提交回复
热议问题