Created
July 9, 2021 10:42
-
-
Save contrasting/8fbb38d20581513ff1c489c02f5c6849 to your computer and use it in GitHub Desktop.
Format unix time into pretty string, WhatsApp style
This file contains hidden or 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
| 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