Last active
June 12, 2019 13:54
-
-
Save markknol/e17a8d58e011000f2549ff46b8e4f2cb to your computer and use it in GitHub Desktop.
DateUtil Outputs "xx days/weeks/days/minutes/seconds ago" https://try.haxe.org/#21f31
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
class DateUtil { | |
public static function format(target:Date) { | |
var secondsInMs = 1000; | |
var minuteInMs = secondsInMs * 60; | |
var hourInMs = minuteInMs * 60; | |
var dayInMs = hourInMs * 24; | |
var targetTime = target.getTime(); | |
var now = Date.now().getTime(); | |
var remainingMs = now - targetTime; | |
var days = Math.floor(remainingMs / dayInMs); | |
var years = Std.int(days / 356); | |
var months = Std.int(days / 30.4167); // should be accurate enough | |
var weeks = Std.int(days / 7); | |
var hours = Std.int(remainingMs / hourInMs); | |
var minutes = Std.int(remainingMs / minuteInMs); | |
var seconds = Std.int(remainingMs / secondsInMs); | |
inline function s(v:Int) return if (v < 2) "" else "s"; | |
return if (years == 0) | |
if (months < 2) | |
if (weeks < 1) | |
if (days == 0) | |
if (hours == 0) | |
if (minutes == 0) '$seconds second${s(seconds)} ago' | |
else '$minutes minute${s(minutes)} ago' | |
else '$hours hour${s(hours)} ago' | |
else '$days day${s(days)} ago' | |
else '$weeks week${s(weeks)} ago' | |
else '$months months ago' | |
else if (years > 1) '$years years ago' | |
else '$years year ago'; | |
} | |
} |
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
class Test { | |
static function main() { | |
var start = Date.now(); | |
js.Browser.window.setInterval(function() { | |
js.Browser.document.body.innerHTML = DateUtil.format(start); | |
}, 1000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment