Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active March 11, 2025 16:42
Show Gist options
  • Save PlugFox/a94be8655b2adb91336f03bc77513d76 to your computer and use it in GitHub Desktop.
Save PlugFox/a94be8655b2adb91336f03bc77513d76 to your computer and use it in GitHub Desktop.
DateTime to int
int dateToValue(DateTime date) {
assert(date.isUtc, 'DateTime must be in UTC');
return (date.year << 9) | (date.month << 5) | date.day;
}
DateTime valueToDate(int value) =>
DateTime.utc(value >> 9, (value >> 5) & 0xF, value & 0x1F);
int dateTimeToValue(DateTime dateTime) {
assert(dateTime.isUtc, 'DateTime must be in UTC');
return (dateTime.year << 26) |
(dateTime.month << 22) | // MMMM (1–12)
(dateTime.day << 17) | // DDDDD (1–31)
(dateTime.hour << 12) | // HHHHH (0–23)
(dateTime.minute << 6) | // MMMMMM (0–59)
dateTime.second; // SSSSSS (0–59)
}
DateTime valueToDateTime(int value) => DateTime.utc(
value >> 26, // Год
(value >> 22) & 0xF, // Месяц (4 бита)
(value >> 17) & 0x1F, // День (5 бит)
(value >> 12) & 0x1F, // Часы (5 бит)
(value >> 6) & 0x3F, // Минуты (6 бит)
value & 0x3F, // Секунды (6 бит)
);
void main() {
void expect(DateTime a, DateTime b) {
final $a = a.millisecondsSinceEpoch, $b = b.millisecondsSinceEpoch;
if ($a == $b) return;
throw Exception('${a.toUtc()} != ${b.toUtc()}');
}
final dates = [
DateTime.utc(0),
DateTime.utc(2021, 1, 1),
DateTime.utc(2021, 1, 1, 1, 1, 1),
DateTime.utc(2024, 10, 10, 10, 10, 10),
DateTime.utc(-10, 10, 10, 10, 10, 10),
DateTime.utc(3000, 12, 30, 23, 59, 59),
];
for (final dt in dates) {
final date = DateTime.utc(dt.year, dt.month, dt.day);
// Проверка конвертации даты
expect(valueToDate(dateToValue(date)), date);
// Проверка конвертации даты и времени
expect(valueToDateTime(dateTimeToValue(dt)), dt);
// Проверка компактности
final DateTime(:year, :month, :day, :hour, :minute, :second) = dt;
final text = [
year,
month,
day,
hour,
minute,
second,
].map((e) => e.toString().padLeft(2, '0')).join('');
if (text.length < dateTimeToValue(dt).toString().length) {
throw Exception('$text is more compact than ${dateTimeToValue(dt)}');
}
}
// 5 Mar. 2025 12:34:56
// ignore: avoid_print
print(dateTimeToValue(DateTime.utc(2025, 03, 05, 12, 34, 56)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment