72 lines
1.7 KiB
Dart
72 lines
1.7 KiB
Dart
import 'package:intl/intl.dart';
|
|
import 'package:timezone/data/latest.dart' as tz_data;
|
|
import 'package:timezone/timezone.dart' as tz;
|
|
|
|
/// Heure métier alignée sur le fuseau du serveur API (pas l'UTC ni le téléphone).
|
|
abstract final class ServerTime {
|
|
static const defaultTimezone = 'Europe/Paris';
|
|
|
|
static bool _initialized = false;
|
|
static tz.Location _location = tz.UTC;
|
|
|
|
static Future<void> initialize({String timezone = defaultTimezone}) async {
|
|
if (!_initialized) {
|
|
tz_data.initializeTimeZones();
|
|
_initialized = true;
|
|
}
|
|
setTimezone(timezone);
|
|
}
|
|
|
|
static void setTimezone(String timezone) {
|
|
if (!_initialized) {
|
|
tz_data.initializeTimeZones();
|
|
_initialized = true;
|
|
}
|
|
_location = tz.getLocation(timezone);
|
|
}
|
|
|
|
static String get timezone => _location.name;
|
|
|
|
static tz.TZDateTime now() => tz.TZDateTime.now(_location);
|
|
|
|
static DateTime startOfToday() {
|
|
final current = now();
|
|
return DateTime(current.year, current.month, current.day);
|
|
}
|
|
|
|
static DateTime? parse(String? iso) {
|
|
if (iso == null || iso.isEmpty) {
|
|
return null;
|
|
}
|
|
return DateTime.tryParse(iso);
|
|
}
|
|
|
|
static tz.TZDateTime toServerTime(DateTime dateTime) {
|
|
return tz.TZDateTime.from(dateTime.toUtc(), _location);
|
|
}
|
|
|
|
static String format(
|
|
DateTime? dateTime, {
|
|
required String pattern,
|
|
String locale = 'fr_FR',
|
|
}) {
|
|
if (dateTime == null) {
|
|
return '';
|
|
}
|
|
|
|
final server = toServerTime(dateTime);
|
|
return DateFormat(pattern, locale).format(
|
|
DateTime(
|
|
server.year,
|
|
server.month,
|
|
server.day,
|
|
server.hour,
|
|
server.minute,
|
|
server.second,
|
|
server.millisecond,
|
|
server.microsecond,
|
|
),
|
|
);
|
|
}
|
|
}
|