nakama/backend/utils/moscowTime.js

80 lines
2.8 KiB
JavaScript
Raw 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);
}
/**
* Получить начало дня по московскому времени
*/
function getMoscowStartOfDay(date = null) {
const moscowTime = date ? new Date(date.getTime()) : getMoscowTime();
moscowTime.setHours(0, 0, 0, 0);
return moscowTime;
}
/**
* Получить текущую дату по московскому времени (начало дня)
*/
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
};