check.js


var assert = require('assert');
var date = require('./index.js');
 
var time = date('2017-05-16 13:45')
    .add(24, 'hours')
    .subtract(1, 'months')
    .add(3, 'days')
    .add(15, 'minutes');
assert.deepEqual(
    time.value,
    '2017-04-20 14:00', 
    'Если к дате "2017-05-16 13:45" ' +
    'прибавить 24 часа, 3 дня и 15 минут, вычесть 1 месяц, ' +
    'то получится "2017-04-20 14:00"'
);

index.js


/**
 * @param {String} date
 * @returns {Object}
 */
module.exports = function (date) {
    var obj = {
        //value: '2017-04-20 14:00',
        init: function(date) {
            if(date instanceof Date) this.newDate = date;
            else {
            var arr = date.split(/[\s:-]/);
            this.newDate = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3], arr[4]));
        }
            return this;
        },
        add: function(value, type) {
                if (value > 0 && type in this.method) {
                    return this.setValue(value, this.method[type]);
                } else {
                    throw new TypeError("Передано неверное значение");
                }
        },
        subtract: function(value, type) {
            if (value > 0 && type in this.method) {
                return this.setValueSubtract(value, this.method[type]);
            } else {
                throw new TypeError("Передано неверное значение");
            }
        },
        method: {
            "years": "FullYear",
            "months": "Month",
            "days": "Date",
            "hours": "Hours",
            "minutes": "Minutes"
        },
        setValue: function(value, method) {
            this.newDate['setUTC' + method](value + this.newDate['getUTC' + method]());
            return this;
        },
        setValueSubtract: function(value, method) {
            this.newDate['setUTC' + method](-value + this.newDate['getUTC' + method]());
            return this;
        },
        toString: function() {
            var year = this.newDate.getFullYear();
            var month = this.newDate.toLocaleString("ru",{timeZone : "UTC",month: '2-digit'});
            var day = this.newDate.toLocaleString("ru",{timeZone : "UTC",day: '2-digit'});
            var time = this.newDate.toLocaleString("ru",{timeZone : "UTC", hour: '2-digit', minute: '2-digit' });
            var dates = year + "-" + month + "-" + day + " " + time;
            return dates;
        }
    };
    return obj.init(date);
};

Gtufc Default Asked on February 18, 2018 in Programming.
Add Comment
  • 0 Answer(s)
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.