Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Операции сложения и вычитания с входной датой (https://javascript.ru/forum/misc/84232-operacii-slozheniya-i-vychitaniya-s-vkhodnojj-datojj.html)

NovichokJS 14.07.2022 15:26

Операции сложения и вычитания с входной датой
 
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 14.07.2022 17:48

Рони, вы где???)

рони 14.07.2022 17:49

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);

NovichokJS 14.07.2022 17:54

спасибо. Буду разбирать ваш код, пока ничего не понял))
Но у меня тоже код рабочий вроде ж как, только не пойму какое выражение составить в метод result(). Можете помочь?

рони 14.07.2022 17:59

Цитата:

Сообщение от NovichokJS
не пойму

строки 8, 11, ... 47, ... 53
resultDate = initValue.setFullYear(initValue.getFullYear() - number) ;

NovichokJS 14.07.2022 18:15

вот так ?

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;
    },

NovichokJS 14.07.2022 18:20

как теперь получить данные в таком формате?
// Output: Jan 15 2019 17:19:17.....

рони 14.07.2022 18:24

Цитата:

Сообщение от NovichokJS
как теперь получить данные в таком формате?

всё должно работать если вы не допустили ошибок

NovichokJS 14.07.2022 18:27

Цитата:

Сообщение от рони (Сообщение 546657)
всё должно работать если вы не допустили ошибок

оно возвращает мне такой формат:
2019-01-10T15:19:17.000Z

voraa 14.07.2022 18:35

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)

рони 14.07.2022 18:37

NovichokJS,
нельзя изменить день, можно только дату!!!

рони 14.07.2022 18:38

voraa,
:)

NovichokJS 14.07.2022 18:39

Voraa, спасибо, но мне надо преобразовать один момент в моем коде только. Мне нужно формат просто задать правильный, выше я спросил это у Рони уже.

рони 14.07.2022 18:41

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);

NovichokJS 14.07.2022 18:41

Цитата:

Сообщение от рони (Сообщение 546660)
NovichokJS,
нельзя изменить день, можно только дату!!!

ок, мне просто надо чтоб в таком формате выводилась
Jan 15 2019 17:19:17...

Потому что сейчас выводится вот в таком:
2019-01-10T15:19:17.000Z

NovichokJS 14.07.2022 18:44

Цитата:

Сообщение от рони (Сообщение 546663)
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);

я понял, я так исправил, но такой вариант возвращает дату в формате
2019-01-15T15:19:17.000Z


Мне же нужно в таком формате:
Jan 15 2019 17:19:17

рони 14.07.2022 18:44

Цитата:

Сообщение от рони
нельзя изменить день, можно только дату!!!

Цитата:

Сообщение от NovichokJS
 resultDate = initValue.setDate(initValue.getDay() - number);

:-?

рони 14.07.2022 18:59

Цитата:

Сообщение от NovichokJS
Мне же нужно в таком формате:
Jan 15 2019 17:19:17

https://learn.javascript.ru/intl
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);

NovichokJS 14.07.2022 19:03

Цитата:

Сообщение от рони (Сообщение 546666)
:-?

ок, у меня сейчас эта переменная resultDate никакой функции не выполняет. Я удалил её с кода и результат не изменился. Мне нужно чтобы входная дата не менялась. Как поправить это?

рони 14.07.2022 19:06

Цитата:

Сообщение от NovichokJS
Мне нужно чтобы входная дата не менялась. Как поправить это?

const getNewDate = initValue => {
            initValue = new Date(initValue);

voraa 14.07.2022 19:10

Вообще с датами все не просто.
Какая дата получится, если к 30 апреля прибавить 1 месяц и 1 день?
А если прибавить 1 день и 1 месяц?
А как правильно то?

рони 14.07.2022 19:36

Цитата:

Сообщение от voraa
А как правильно то?

я так считаю)))-- сначала месяц потом день
и того 31 марта.
https://javascript.ru/forum/misc/687...momenta-2.html
http://javascript.ru/forum/misc/1280...html#post77682

voraa 14.07.2022 19:57

Да хрен его знает.
Я вот чисто житейски не всегда понимаю.
Если мне 31 мая скажут приходите через месяц, то я не пойму это 30 июня или 1 июля?

рони 14.07.2022 20:02

voraa,
у кого как, но обычно 30 июня очередной транш)))


Часовой пояс GMT +3, время: 06:16.