Skip to content

Instantly share code, notes, and snippets.

@contrasting
Created July 9, 2021 10:42
Show Gist options
  • Select an option

  • Save contrasting/8fbb38d20581513ff1c489c02f5c6849 to your computer and use it in GitHub Desktop.

Select an option

Save contrasting/8fbb38d20581513ff1c489c02f5c6849 to your computer and use it in GitHub Desktop.
Format unix time into pretty string, WhatsApp style
final yMMMd = DateFormat.yMMMd();
final MMMd = DateFormat.MMMd();
final E = DateFormat.E().add_d();
final Hm = DateFormat.Hm();
String formatUnixTime(int unixMilli) {
final sentTime = DateTime.fromMillisecondsSinceEpoch(unixMilli);
final currTime = DateTime.now();
DateFormat formatter;
if (currTime.year - sentTime.year > 0) {
// different year
formatter = yMMMd;
} else if (currTime.month - sentTime.month > 0) {
// same year, different month
formatter = MMMd;
} else if (currTime.day - sentTime.day > 0) {
// same month, different day
formatter = currTime.day - sentTime.day >= 7 ? MMMd : E;
} else {
// same day
return 'Today';
}
return formatter.format(sentTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment