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)


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