js獲取本周/本月時間


轉自於:https://www.cnblogs.com/tlfe/p/12124204.html

var now = new Date(); // 當前日期
var nowDayOfWeek = now.getDay(); // 今天本周的第幾天
var nowDay = now.getDate(); // 當前日
var nowMonth = now.getMonth(); // 當前月
var nowYear = now.getYear(); // 當前年
nowYear += (nowYear < 2000) ? 1900 : 0;
 
var DateUtil = {
    /**
     * 獲得當前日期
     * 
     * @returns
     */
    getNowDay() {
        return this.formatDate(new Date());
    },
    /**
     * 獲得本周的開始時間
     * 
     * @returns
     */
    getStartDayOfWeek() {
        var day = nowDayOfWeek || 7;
        return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));
    },
    /**
     * 獲得本周的結束時間
     * 
     * @returns
     */
    getEndDayOfWeek() {
        var day = nowDayOfWeek || 7;
        return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 7 - day));
    },
    /**
     * 獲得本月的開始時間
     * 
     * @returns
     */
    getStartDayOfMonth() {
        var monthStartDate = new Date(nowYear, nowMonth, 1);
        return this.formatDate(monthStartDate);
    },
    /**
     * 獲得本月的結束時間
     * 
     * @returns
     */
    getEndDayOfMonth() {
        var monthEndDate = new Date(nowYear, nowMonth, this.getMonthDays());
        return this.formatDate(monthEndDate);
    },
    /**
     * 獲得本月天數
     * 
     * @returns
     */
    getMonthDays() {
        var monthStartDate = new Date(nowYear, nowMonth, 1);
        var monthEndDate = new Date(nowYear, nowMonth + 1, 1);
        var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
    },
    /**
     * @param 日期格式化
     * @returns {String}
     */
    formatDate(date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();
 
        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    }
};

export default{
    DateUtil
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM