怎么实现一个计算一年中有多少周?

  1. 首先你得知道是不是闰年,也就是一年是365还是366。
  2. 其次你得知道当年1月1号是周几。假如是周五,一年365天把1号 2号3号减去,也就是把第一个不到一周的天数减去等于362,还得知道最后一天是周几,假如是周五,需要把周一到周五减去,也就是362-5=357。正常情况 357这个数计算出来是7的倍数。357/7=51 。即为周数。
获取某年某月某日是星球几

    function getDate(date) {
        let oDate = new Date(date)
        let day = oDate.getDay()
        console.log(typeof day)
        switch (day) {
            case 0:
                console.log('星期日')
                return 0
            case 1:
                console.log('星期一')
                return 1
            case 2:
                console.log('星期二')
                return 2
            case 3:
                console.log('星期三')
                return 3
            case 4:
                console.log('星期四')
                return 4
            case 5:
                console.log('星期五')
                return 5
            case 6:
                console.log('星期六')
                return 6
        }

    }
整体代码实现:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<script>
    //判断是否是闰年
    function isLeapYear(year) {
        if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
            console.log(year + 'is leap year')
            return true

        } else {
            console.log(year + 'is not leap year')
            return false
        }
    }

    //获取某年某月某日是星球几
    function getDate(date) {
        let oDate = new Date(date)
        let day = oDate.getDay()
        console.log(typeof day)
        switch (day) {
            case 0:
                console.log('星期日')
                return 0
            case 1:
                console.log('星期一')
                return 1
            case 2:
                console.log('星期二')
                return 2
            case 3:
                console.log('星期三')
                return 3
            case 4:
                console.log('星期四')
                return 4
            case 5:
                console.log('星期五')
                return 5
            case 6:
                console.log('星期六')
                return 6
        }

    }

    function main() {
        let currentYearDays = isLeapYear(2019) ? 366 : 365
        let beforeDays = 7 - getDate('2019-1-1')+1
        let afterDays = getDate('2019-12-31')
        let vaildDays = currentYearDays - beforeDays - afterDays
        let weeks = vaildDays / 7
        console.log(weeks)

    }
    main()

script>
body>
html>

你可能感兴趣的:(前端开发)