Операции сложения и вычитания с входной датой
const getNewDate = initValue => { let resultDate = initValue; const newValue = { add(dateInterval, number) { switch (dateInterval) { case 'years': resultDate = initValue.getFullYear() + number; break; case 'months': resultDate = initValue.getMonth() + number; break; case 'days': resultDate = initValue.getDay() + number; break; case 'hours': resultDate = initValue.getHours() + number; break; case 'minutes': resultDate = initValue.getMinutes() + number; break; case 'seconds': resultDate = initValue.getSeconds() + number; break; case 'milliseconds': resultDate = initValue.getMilliseconds() + number; break; } return this; }, subtract(dateInterval, number) { switch (dateInterval) { case 'years': resultDate = initValue.getFullYear() - number; break; case 'months': resultDate = initValue.getMonth() - number; break; case 'days': resultDate = initValue.getDay() - number; break; case 'hours': resultDate = initValue.getHours() - number; break; case 'minutes': resultDate = initValue.getMinutes() - number; break; case 'seconds': resultDate = initValue.getSeconds() - number; break; case 'milliseconds': resultDate = initValue.getMilliseconds() - number; break; } return this; }, result() { return resultDate; }, }; return newValue; }; const res = getNewDate(new Date(2020, 0, 7, 17, 17, 17)) .add('minutes', 2) .add('days', 8) .subtract(years, 1) .result(); // Output: ...Jan 15 2019 17:19:17..... console.log(res); Помогите плиз доделать чтобы работало. Функция принимает входящую дату и возвращать объект с набором методов. Метод result должен вернуть новую дату после всех преобразований. Цепочка вызова методов может быть в любом порядке. Словом, мне нужно сделать правильное выражение в методе result() { return .....; } |
Рони, вы где???)
|
NovichokJS,
:-? const getNewDate = initValue => { const newValue = { add(property, value) { let set = `${property == 'year' ? 'setFull' : 'set'}`; let get = `${property == 'year' ? 'getFull' : 'get'}`; property = `${property.slice(0,1).toUpperCase()}${property.slice(1)}`; set += property; get += property; value += initValue[get](); initValue[set](value); return this; }, subtract(property, value) { this.add(property, -value) return this; }, result() { return initValue; }, }; return newValue; }; const res = getNewDate(new Date(2020, 0, 7, 17, 17, 17)) .add('minutes', 2) .add('date', 8) .subtract('year', 1) .result(); // Output: ...Jan 15 2019 17:19:17..... console.log(res); |
спасибо. Буду разбирать ваш код, пока ничего не понял))
Но у меня тоже код рабочий вроде ж как, только не пойму какое выражение составить в метод result(). Можете помочь? |
Цитата:
resultDate = initValue.setFullYear(initValue.getFullYear() - number) ; |
вот так ?
subtract(dateInterval, number) { switch (dateInterval) { case 'years': resultDate = initValue.setFullYear(initValue.getFullYear() - number); break; case 'months': resultDate = initValue.setMonth(initValue.getMonth() - number); break; case 'days': resultDate = initValue.setDate(initValue.getDay() - number); break; case 'hours': resultDate = initValue.setHours(initValue.getHours() - number); break; case 'minutes': resultDate = initValue.setMinutes(initValue.getMinutes() - number); break; case 'seconds': resultDate = initValue.setSeconds(initValue.getSeconds() - number); break; case 'milliseconds': resultDate = initValue.setMilliseconds(initValue.getMilliseconds() - number); break; } return this; }, |
как теперь получить данные в таком формате?
// Output: Jan 15 2019 17:19:17..... |
Цитата:
|
Цитата:
2019-01-10T15:19:17.000Z |
class CDate extends Date { constructor (...args) { super (...args) } add (what) { if (what.seconds) { this.setTime(this.valueOf() + what.seconds*1000); } if (what.minutes) { this.setTime(this.valueOf() + what.minutes*60*1000); } if (what.hours) { this.setTime(this.valueOf() + what.hours*60*60*1000); } if (what.days) { this.setTime(this.valueOf() + what.days*24*60*60*1000); } if (what.weeks) { this.setTime(this.valueOf() + what.weeks*7*24*60*60*1000); } if (what.months) { let curm = this.getMonth(); let cury = this.getFullYear(); cury += what.months / 12 | 0; curm += what.months % 12; if (curm >=12) { curm -= 12; cury ++; } const nd = new Date (cury, curm, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); this.setTime(nd.valueOf()); } if (what.years) { let cury = this.getFullYear() + what.years; const nd = new Date (cury, this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); this.setTime(nd.valueOf()); } } sub (what) { this.add ({ years: - (what.years||0), months: - (what.months||0), weeks: - (what.weeks||0), days: - (what.days||0), hours: - (what.hours||0), minutes: - (what.minutes||0), seconds: - (what.seconds||0), } ) } } dt = new CDate(); console.log (dt) dt.add({months:15, weeks:2, days:4, hours: 10, minutes:50}) console.log ('add', dt) dt1 = new CDate(); console.log (dt1) dt1.sub({years: 3, months:10, weeks:2, minutes:18}) console.log ('sub', dt1) |
NovichokJS,
нельзя изменить день, можно только дату!!! |
voraa,
:) |
Voraa, спасибо, но мне надо преобразовать один момент в моем коде только. Мне нужно формат просто задать правильный, выше я спросил это у Рони уже.
|
NovichokJS,
... исправленный вариант со switch const getNewDate = initValue => { const newValue = { add(dateInterval, number) { switch (dateInterval) { case 'years': initValue.setFullYear(initValue.getFullYear() + number); break; case 'months': initValue.setMonth(initValue.getMonth() + number); break; case 'days': initValue.setDate(initValue.getDate() + number); break; case 'hours': initValue.setHours(initValue.getHours() + number); break; case 'minutes': initValue.setMinutes(initValue.getMinutes() + number); break; case 'seconds': initValue.setSeconds(initValue.getSeconds() + number); break; case 'milliseconds': initValue.setMilliseconds(initValue.getMilliseconds() + number); break; } return this; }, subtract(dateInterval, number) { switch (dateInterval) { case 'years': initValue.setFullYear(initValue.getFullYear() - number); break; case 'months': initValue.setMonth(initValue.getMonth() - number); break; case 'days': initValue.setDate(initValue.getDate() - number); break; case 'hours': initValue.setHours(initValue.getHours() - number); break; case 'minutes': initValue.setMinutes(initValue.getMinutes() - number); break; case 'seconds': initValue.setSeconds(initValue.getSeconds() - number); break; case 'milliseconds': initValue.setMilliseconds(initValue.getMilliseconds() - number); break; } return this; }, result() { return initValue; }, }; return newValue; }; const res = getNewDate(new Date(2020, 0, 7, 17, 17, 17)) .add('minutes', 2) .add('days', 8) .subtract('years', 1) .result(); // Output: ...Jan 15 2019 17:19:17..... console.log(res); |
Цитата:
Jan 15 2019 17:19:17... Потому что сейчас выводится вот в таком: 2019-01-10T15:19:17.000Z |
Цитата:
2019-01-15T15:19:17.000Z Мне же нужно в таком формате: Jan 15 2019 17:19:17 |
Цитата:
Цитата:
|
Цитата:
const getNewDate = initValue => { const newValue = { add(dateInterval, number) { switch (dateInterval) { case 'years': initValue.setFullYear(initValue.getFullYear() + number); break; case 'months': initValue.setMonth(initValue.getMonth() + number); break; case 'days': initValue.setDate(initValue.getDate() + number); break; case 'hours': initValue.setHours(initValue.getHours() + number); break; case 'minutes': initValue.setMinutes(initValue.getMinutes() + number); break; case 'seconds': initValue.setSeconds(initValue.getSeconds() + number); break; case 'milliseconds': initValue.setMilliseconds(initValue.getMilliseconds() + number); break; } return this; }, subtract(dateInterval, number) { switch (dateInterval) { case 'years': initValue.setFullYear(initValue.getFullYear() - number); break; case 'months': initValue.setMonth(initValue.getMonth() - number); break; case 'days': initValue.setDate(initValue.getDate() - number); break; case 'hours': initValue.setHours(initValue.getHours() - number); break; case 'minutes': initValue.setMinutes(initValue.getMinutes() - number); break; case 'seconds': initValue.setSeconds(initValue.getSeconds() - number); break; case 'milliseconds': initValue.setMilliseconds(initValue.getMilliseconds() - number); break; } return this; }, result() { let formatter = new Intl.DateTimeFormat("en", { month: "short", year: 'numeric', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); return formatter.format(initValue); }, }; return newValue; }; const res = getNewDate(new Date(2020, 0, 7, 17, 17, 17)) .add('minutes', 2) .add('days', 8) .subtract('years', 1) .result(); // Output: ...Jan 15 2019 17:19:17..... console.log(res); |
Цитата:
|
Цитата:
const getNewDate = initValue => { initValue = new Date(initValue); |
Вообще с датами все не просто.
Какая дата получится, если к 30 апреля прибавить 1 месяц и 1 день? А если прибавить 1 день и 1 месяц? А как правильно то? |
Цитата:
и того 31 марта. https://javascript.ru/forum/misc/687...momenta-2.html http://javascript.ru/forum/misc/1280...html#post77682 |
Да хрен его знает.
Я вот чисто житейски не всегда понимаю. Если мне 31 мая скажут приходите через месяц, то я не пойму это 30 июня или 1 июля? |
voraa,
у кого как, но обычно 30 июня очередной транш))) |
Часовой пояс GMT +3, время: 06:16. |