MIF_E31222656/lib/utils/date_formatter.dart

47 lines
1.6 KiB
Dart

import 'package:intl/intl.dart';
/// Format a DateTime to a readable string format (e.g., "12 Jan 2023")
String formatDate(DateTime date) {
return DateFormat('d MMM yyyy').format(date);
}
/// Format a DateTime to a readable string format with time (e.g., "12 Jan 2023, 14:30")
String formatDateWithTime(DateTime date) {
return DateFormat('d MMM yyyy, HH:mm').format(date);
}
/// Format a DateTime to show only the day and month (e.g., "12 Jan")
String formatDayMonth(DateTime date) {
return DateFormat('d MMM').format(date);
}
/// Format a DateTime to show only the month and year (e.g., "Jan 2023")
String formatMonthYear(DateTime date) {
return DateFormat('MMM yyyy').format(date);
}
/// Calculate the difference between two dates in days
int daysBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
/// Returns a human-readable string representing the time elapsed since the given date
String timeAgo(DateTime date) {
final difference = DateTime.now().difference(date);
if (difference.inDays > 365) {
return '${(difference.inDays / 365).floor()} tahun yang lalu';
} else if (difference.inDays > 30) {
return '${(difference.inDays / 30).floor()} bulan yang lalu';
} else if (difference.inDays > 0) {
return '${difference.inDays} hari yang lalu';
} else if (difference.inHours > 0) {
return '${difference.inHours} jam yang lalu';
} else if (difference.inMinutes > 0) {
return '${difference.inMinutes} menit yang lalu';
} else {
return 'Baru saja';
}
}