nakama/backend/utils/moscowTime.js

104 lines
4.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Утилиты для работы с московским временем (MSK, UTC+3)
*/
/**
* Получить текущее московское время
*/
function getMoscowTime() {
const now = new Date();
// Москва = UTC+3
// Получаем UTC время и добавляем 3 часа
const utcTime = now.getTime() + (now.getTimezoneOffset() * 60 * 1000);
const moscowOffset = 3 * 60 * 60 * 1000; // 3 часа в миллисекундах
return new Date(utcTime + moscowOffset);
}
/**
* Получить начало дня по московскому времени
* Принимает дату (может быть в UTC или локальном времени)
* Возвращает дату с началом дня по московскому времени (UTC+3)
*/
function getMoscowStartOfDay(date = null) {
let moscowTime;
if (date) {
// Если дата передана, конвертируем её в московское время
const dateObj = new Date(date);
// Получаем UTC timestamp
const utcTimestamp = dateObj.getTime();
// Добавляем московское смещение (UTC+3)
const moscowOffset = 3 * 60 * 60 * 1000;
moscowTime = new Date(utcTimestamp + moscowOffset);
} else {
moscowTime = getMoscowTime();
}
// Устанавливаем начало дня (00:00:00) в московском времени
// Используем UTC методы для правильной работы с часовыми поясами
const year = moscowTime.getUTCFullYear();
const month = moscowTime.getUTCMonth();
const day = moscowTime.getUTCDate();
// Создаем новую дату с началом дня в московском времени
// Создаем UTC дату для нужного дня, затем вычитаем 3 часа для получения правильного UTC timestamp
const moscowStartOfDay = new Date(Date.UTC(year, month, day, 0, 0, 0, 0));
const moscowOffset = 3 * 60 * 60 * 1000;
return new Date(moscowStartOfDay.getTime() - moscowOffset);
}
/**
* Получить текущую дату по московскому времени (начало дня)
*/
function getMoscowDate() {
return getMoscowStartOfDay();
}
/**
* Форматировать дату в московское время для логов
*/
function formatMoscowTime(date = null) {
const moscowTime = date ? new Date(date.getTime()) : getMoscowTime();
const year = moscowTime.getFullYear();
const month = String(moscowTime.getMonth() + 1).padStart(2, '0');
const day = String(moscowTime.getDate()).padStart(2, '0');
const hours = String(moscowTime.getHours()).padStart(2, '0');
const minutes = String(moscowTime.getMinutes()).padStart(2, '0');
const seconds = String(moscowTime.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} MSK`;
}
/**
* Проверить, является ли дата сегодняшней по московскому времени
*/
function isMoscowToday(date) {
const today = getMoscowStartOfDay();
const checkDate = getMoscowStartOfDay(date);
return today.getTime() === checkDate.getTime();
}
/**
* Получить новогоднюю дату по московскому времени (1 января следующего года, 00:00 MSK)
*/
function getNewYearMoscow() {
const now = getMoscowTime();
const year = now.getFullYear() + 1;
// Создаем дату 1 января следующего года в московском времени
// Используем UTC и вычитаем смещение для получения правильного UTC времени
const moscowNewYear = new Date(Date.UTC(year, 0, 1, 0, 0, 0, 0));
// Вычитаем 3 часа, чтобы получить UTC время, которое при добавлении 3 часов даст 00:00 MSK
const moscowOffset = 3 * 60 * 60 * 1000;
return new Date(moscowNewYear.getTime() - moscowOffset);
}
module.exports = {
getMoscowTime,
getMoscowStartOfDay,
getMoscowDate,
formatMoscowTime,
isMoscowToday,
getNewYearMoscow
};