90 lines
2.5 KiB
Dart
90 lines
2.5 KiB
Dart
import 'package:flutter/material.dart';
|
||
import 'package:timezone/data/latest.dart' as tz;
|
||
import 'package:timezone/timezone.dart' as tz;
|
||
|
||
class AppTime {
|
||
static bool _initialized = false;
|
||
|
||
static void initialize({String location = 'Asia/Manila'}) {
|
||
if (_initialized) return;
|
||
tz.initializeTimeZones();
|
||
tz.setLocalLocation(tz.getLocation(location));
|
||
_initialized = true;
|
||
}
|
||
|
||
static DateTime now() {
|
||
return tz.TZDateTime.now(tz.local);
|
||
}
|
||
|
||
static DateTime nowUtc() {
|
||
return now().toUtc();
|
||
}
|
||
|
||
static DateTime toAppTime(DateTime value) {
|
||
final utc = value.isUtc ? value : value.toUtc();
|
||
return tz.TZDateTime.from(utc, tz.local);
|
||
}
|
||
|
||
static DateTime parse(String value) {
|
||
return toAppTime(DateTime.parse(value));
|
||
}
|
||
|
||
/// Converts a [DateTime] into a human-readable short date string.
|
||
///
|
||
/// Example: **Jan 05, 2025**. This matches the format previously used by
|
||
/// `_formatDate` helpers across multiple screens.
|
||
static String formatDate(DateTime value) {
|
||
const months = [
|
||
'Jan',
|
||
'Feb',
|
||
'Mar',
|
||
'Apr',
|
||
'May',
|
||
'Jun',
|
||
'Jul',
|
||
'Aug',
|
||
'Sep',
|
||
'Oct',
|
||
'Nov',
|
||
'Dec',
|
||
];
|
||
final month = months[value.month - 1];
|
||
final day = value.day.toString().padLeft(2, '0');
|
||
return '$month $day, ${value.year}';
|
||
}
|
||
|
||
/// Formats a [DateTimeRange] as ``start - end`` using [formatDate].
|
||
static String formatDateRange(DateTimeRange range) {
|
||
return '${formatDate(range.start)} - ${formatDate(range.end)}';
|
||
}
|
||
|
||
/// Renders a [DateTime] in 12‑hour clock notation with AM/PM suffix.
|
||
///
|
||
/// Example: **08:30 PM**. Used primarily in workforce-related screens.
|
||
/// Creates a [DateTime] in the app timezone (Asia/Manila) from date/time components.
|
||
///
|
||
/// Use this instead of [DateTime] constructor when building a Manila-aware
|
||
/// timestamp from separate year/month/day/hour/minute values so that
|
||
/// `.toUtc()` correctly accounts for the +08:00 offset.
|
||
static DateTime fromComponents({
|
||
required int year,
|
||
required int month,
|
||
required int day,
|
||
int hour = 0,
|
||
int minute = 0,
|
||
}) {
|
||
return tz.TZDateTime(tz.local, year, month, day, hour, minute);
|
||
}
|
||
|
||
static String formatTime(DateTime value) {
|
||
final rawHour = value.hour;
|
||
final hour = (rawHour % 12 == 0 ? 12 : rawHour % 12).toString().padLeft(
|
||
2,
|
||
'0',
|
||
);
|
||
final minute = value.minute.toString().padLeft(2, '0');
|
||
final suffix = rawHour >= 12 ? 'PM' : 'AM';
|
||
return '$hour:$minute $suffix';
|
||
}
|
||
}
|