Last active
November 13, 2023 13:45
-
-
Save obumnwabude/3b5718978f971b0c489cd816d03964ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:intl/intl.dart'; | |
extension DateTimeX on DateTime { | |
bool get isToday { | |
return now.day == day && now.month == month && now.year == year; | |
} | |
bool get isYesterday { | |
return now.day - 1 == day && now.month == month && now.year == year; | |
} | |
bool get isInThisWeek { | |
return (now.day - day).abs() < 7 && now.month == month && now.year == year; | |
} | |
bool get isInThisYear => year == now.year; | |
DateTime get now => DateTime.now(); | |
bool get isInThePastHour => isToday && now.hour == hour; | |
// The day of this DateTime relative to now. Just the day or the month | |
// date depending on whcih is further. Useful for separating a group | |
// of activities (chat messages for example) in the same day. | |
String get dayDisplay { | |
if (isToday) return 'Today'; | |
if (isYesterday) return 'Yesterday'; | |
final format = 'EEEE${isInThisWeek ? '' : ', d MMM'}' | |
'${isInThisYear ? '' : ', yyyy'}'; | |
return DateFormat(format).format(this); | |
} | |
// The time or day relative to now. | |
// Useful for dates on lists of snippets | |
String get overviewDisplay { | |
if (isInThePastHour) { | |
final mins = now.difference(this).inMinutes; | |
return mins == 0 ? 'Now' : '$mins min${mins == 1 ? '' : 's'}'; | |
} | |
if (isYesterday) return 'Yesterday'; | |
final String format; | |
if (isToday) { | |
format = 'HH:mm'; | |
} else if (isInThisWeek) { | |
format = 'EEE'; | |
} else if (isInThisYear) { | |
format = 'MMM d'; | |
} else { | |
format = 'MMM yyyy'; | |
} | |
return DateFormat(format).format(this); | |
} | |
// The exact time relative till now. Prefixes day, month, or year | |
// as is necessary. Useful for details. | |
String get timeDisplay { | |
if (isYesterday) return 'Yesterday ${DateFormat('HH:mm').format(this)}'; | |
final String format; | |
if (isToday) { | |
format = 'HH:mm'; | |
} else if (isInThisWeek) { | |
format = 'EEE HH:mm'; | |
} else if (isInThisYear) { | |
format = 'MMM d, HH:mm'; | |
} else { | |
format = 'dd/MM/yy, HH:mm'; | |
} | |
return DateFormat(format).format(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment