JS 實作 #14 | 顯示日期;Date()、getFullYear()

這節學習如何在 Javascript 中顯示日期。

開始實作

1. 在 UI CONTROLLER 裡新增公開的 displayMonth() 方法,並且在GLOBAL APP CONTROLLER init() 裡面呼叫它。

// UI CONTROLLER
var UIController = (function() {

    var DOMstrings = {
        ...
    };

    var formatNumber = function(num, type) {
        ...
    };

    return {
        getInput: function() {
            ...
        },
        getDOMstrings: function() {
            return DOMstrings;
        },
        addListItem: function(obj, type) {
						...
        },
        deleteListItems: function(selectorID) {
            ...
        },
        clearFields: function () {
            ...
        },
        displayBudget: function(obj) {
            ...
        },
        displayPercentages: function(percentages) {
            ...
        },
        **displayMonth: function() {
            // to do 
        }**
    };

})();
// GLOBAL APP CONTROLLER
var controller = (function(budgetCtrl, UICtrl){

    var setupEventListeners = function() {
        ...
    };
    var updateBudget = function() {
				...
    };

    var updatePercentages = function() {
				...
    };

    var ctrlAddItem = function() {
				...
    };
    var ctrlDeleteItem = function(event) {
	      ...
    };
    
    return {
        init: function() {
            console.log('Application has started.');
            **UICtrl.displayMonth();**
            UICtrl.displayBudget({
                budget: 0,
                totalInc: 0,
                totalExp: 0,
                percentage: -1
            });
            setupEventListeners();
            ui
        }
    }
})(budgetController, UIController);

controller.init();

2. 使用 new Date() 來獲得現在的日期,並且另外使用 getMonth()getFullYear() 來獲得月和年即完成。

// UI CONTROLLER
var UIController = (function() {

    var DOMstrings = {
        ...
    };

    var formatNumber = function(num, type) {
        ...
    };

    return {
        getInput: function() {
            ...
        },
        getDOMstrings: function() {
            return DOMstrings;
        },
        addListItem: function(obj, type) {
						...
        },
        deleteListItems: function(selectorID) {
            ...
        },
        clearFields: function () {
            ...
        },
        displayBudget: function(obj) {
            ...
        },
        displayPercentages: function(percentages) {
            ...
        },
        **displayMonth: function() {
            var now, months, month, year;
            now = new Date();

            months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            month = now.getMonth();
            year = now.getFullYear();

            document.querySelector(DOMstrings.dateLabel).textContent = months[month] + ' ' + year;
        }**
    };

})();

參考更多相關時間的原生函式:

Zeen is a next generation WordPress theme. It’s powerful, beautifully designed and comes with everything you need to engage your visitors and increase conversions.