Рассчитайте дату и время с учетом разницы в каждом дне

#javascript #typescript #date #time #days

Вопрос:

Итак, у меня есть такой диск

 let events = {
      "KOTH Airship": ["EVERY 19:00"],
      "KOTH Castle": ["EVERY 20:00"],
      Totem: ["EVERY 17:00", "EVERY 23:00"],
      Jump: ["Monday 18:00"],
      "Laby PvP": ["Tuesday 18:00"],
      "MegaKOTH Nether": ["Wednesday 18:00"],
      AirDrop: ["Thusday 18:00"],
      "Rain of Items": ["Friday 18:00"],
      "MegaKOTH Pyramid": ["Saturday 18:00"],
      "MegaKOTH End": ["Sunday 18:00"],
    };
 

Я хочу рассчитать время, оставшееся с сегодняшнего дня до следующего дня (с указанием названия дня или следующего дня, т. е. каждого), Как я должен это сделать?

Ответ №1:

Я думаю, «каждый» означает следующий день.

Ваши данные таковы, что:

 [...days|every] [hour, minute]
 

Вот мои коды:

 class EventDate extends Date {
    calculate(data) {
        let result = { day: 0, hour: 0, minute: 0, second: 0 };
        let now = Date.now();
        this.setByParsing(data);

        let diff = this.getTime() - now;
        result.time = diff;
        result.second = diff / 1000;
        result.minute = result.second / 60;
        result.hour = result.minute / 60;
        result.day = result.hour / 24;
        result.second = result.second >= 0 ? Math.floor(result.second % 60) : 0;
        result.minute = result.minute >= 0 ? Math.floor(result.minute % 60) : 0;
        result.hour = result.hour >= 0 ? Math.floor(result.hour % 24) : 0;
        result.day = result.day >= 0 ? Math.floor(result.day) : 0;
        return resu<
    }

    getByParsing(data) {
        let result = {};
        let dayNames = this.getDayNames();
        let parts = data.split(' ');
        let currentDate = new Date();

        if (parts) {
            let pDayName = parts[0].toLowerCase();
            let dayInd = dayNames.indexOf(pDayName);
            let day = this.getDay();
            let date = this.getDate();
            let parsedTime = this.parseTime(data);

            if (dayInd < 0) {
                date  ;
                day  ;
                if (day > 6) day = 0;
            }
            else {
                if (currentDate.getDay() === dayInd amp;amp; this.isTimeEarlier(parsedTime, { hour: currentDate.getHours(), minute: currentDate.getMinutes(), second: currentDate.getSeconds() })) date  = 7;
                else date  = Math.abs(dayInd - day);
                day = dayInd;
            }
        
            result.day = day;
            result.date = date; 
            result = { ...result, ...parsedTime };
        }
    
        return resu<
    }

    setByParsing(data) {
        let parsing = this.getByParsing(data);
        if ('date' in parsing) this.setDate(parsing.date);
        if ('hour' in parsing) this.setHours(parsing.hour);
        if ('minute' in parsing) this.setMinutes(parsing.minute);
        if ('second' in parsing) this.setSeconds(parsing.second);
        return this;
    }

    parseTime(data) {
        let result = { hour: 0, minute: 0, second: 0 };
        let parts = data.split(' ');

        if (parts amp;amp; '1' in parts) {
            let timeParts = parts[1].split(':');
            result.hour = timeParts[0] || 0;
            result.minute = timeParts[1] || 0;
            result.second = timeParts[2] || 0;
        }
    
        return resu<
    }

    isTimeEarlier(time1, time2) {
        if (time1.hour < time2.hour) return true;
        else if (time1.minute < time2.minute) return true;
        else if (time1.second < time2.second) return true;
    }

    getDayNames() {
        let date = new Date();
        date.setDate(date.getDate() - date.getDay());

        return [...Array(7)].map((val, ind) => {
            let result = date.toLocaleString('en-us', { weekday: 'long' });
            date.setDate(date.getDate()   1);
            return result.toLowerCase();
        });
    }
}

let times = {};

Object.keys(events).forEach(name => {
    times[name] = [];
    
    events[name].forEach(data => {
        let dataDate = new EventDate();
        times[name].push(dataDate.calculate(data));
    });
});

console.log(times);
 

Комментарии:

1. Это сработало, как и ожидалось, но я получаю отрицательные даты, если дата уже прошла!

2. Я понял. Вы имеете в виду, что если данные [сегодня] [раннее время], они дают отрицательные числа. Я обновляю ответ.

3. Кроме того, если вы проверяете, истекло время или нет, используйте «[время].время > 0».

4. Я забыл одну строчку. Отредактировано еще раз.

5. теперь все даты положительные, но они стали 0d 0h 0m и 0s. Я хотел, чтобы он был нацелен на предстоящее воскресенье (в случае сегодняшнего дня).