feat: add period, time and name file utils

This commit is contained in:
Petr Rudichev 2025-02-18 19:46:56 +03:00
parent e8eeb0676c
commit 620f7aeffb
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,5 @@
package com.example.nto.utils;
public enum DataFormatType {
DATE_TIME, DATE, TIME
}

View File

@ -0,0 +1,52 @@
package com.example.nto.utils;
import lombok.experimental.UtilityClass;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
@UtilityClass
public class Utils {
private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");
public static String profileFileName(long userId) {
return "profile--" + userId;
}
public static String generateUniqueName() {
return UUID.randomUUID().toString();
}
public static String nowTime(DataFormatType type) {
switch (type) {
case DATE_TIME: return LocalDateTime.now().format(DATE_TIME_FORMAT);
case DATE: return LocalDateTime.now().format(DATE_FORMAT);
case TIME: return LocalDateTime.now().format(TIME_FORMAT);
default: return "Произошла ошибка при форматировании даты или времени.";
}
}
public static LocalDateTime period(LocalDateTime dtStart, LocalDateTime dtEnd) {
// Возвращает разницу между двумя LocalDateTime
Period period = Period.between(dtStart.toLocalDate(), dtEnd.toLocalDate());
Duration duration = Duration.between(dtStart.toLocalTime(), dtEnd.toLocalTime());
LocalDate localDate = LocalDate.of(period.getYears(), period.getMonths(), period.getDays());
LocalTime localTime = LocalTime.of(duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart());
return LocalDateTime.of(localDate, localTime);
}
public static long periods(List<List<LocalDateTime>> periods) {
// Количество часов за определенные периоды.
long hours = 0;
for (List<LocalDateTime> period : periods) {
if (period.size() != 2) throw new IllegalStateException("Список с периодом должен содержать 2 элемента!");
hours += Duration.between(period.get(0), period.get(1)).toHours();
}
return hours;
}
}