import 'package:intl/intl.dart';

class DateUtil {
  DateUtil._();

  static String fromMillisecondsSinceEpoch(String format, int endTimestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(endTimestamp);
    return DateFormat(format).format(date);
  }

  static DateTime getNow({Duration? subtract}) {
    if (subtract == null) {
      return DateTime.now();
    } else {
      return DateTime.now().subtract(subtract);
    }
  }

  static String formatDateTime(DateTime dateTime, String format) {
    return DateFormat(format).format(dateTime);
  }

  //2个时间之差是否超过指定的时间范围，需考虑时间差为负的情况
  static bool isTimeRangeExceed(
      DateTime startTime, DateTime endTime, Duration duration) {
    final diff = endTime.difference(startTime);
    return diff.isNegative ? diff.abs() > duration : diff > duration;
  }

  static bool isTimeIntRangeExceed(int time, int time2, Duration duration) {
    final diff = time2 - time;
    return diff.isNegative
        ? diff.abs() > duration.inSeconds
        : diff > duration.inSeconds;
  }
}

extension DateTimeExt on DateTime {
  String format(String format) {
    return DateFormat(format).format(this);
  }
}
