| 1 |
package website; |
| 2 |
|
| 3 |
/** |
| 4 |
* @author Mark Knol |
| 5 |
*/ |
| 6 |
class Util { |
| 7 |
private static var _MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; |
| 8 |
|
| 9 |
public static function escape(str:String) return StringTools.htmlEscape(str, true); |
| 10 |
|
| 11 |
/** |
| 12 |
Outputs to "xx-Jan 2019" (accurate=true) or "xx days/weeks ago" (accurate=false) |
| 13 |
@param date should be format "yyyy-mm-dd" |
| 14 |
**/ |
| 15 |
public static function formatDate(date:String, accurate:Bool = false) { |
| 16 |
var split = date.split("-"); |
| 17 |
var target:Date = new Date(Std.parseInt(split[0]), Std.parseInt(split[1]) - 1, Std.parseInt(split[2]), 0, 0, 0); |
| 18 |
|
| 19 |
if (!accurate) { // loose date format |
| 20 |
var minuteInMs = 1000 * 60; |
| 21 |
var hourInMs = minuteInMs * 60; |
| 22 |
var dayInMs = hourInMs * 24; |
| 23 |
|
| 24 |
var targetTime = target.getTime(); |
| 25 |
|
| 26 |
var now = Date.now().getTime(); |
| 27 |
var remainingMs = now - targetTime; |
| 28 |
|
| 29 |
var days = Math.floor(remainingMs / dayInMs); |
| 30 |
var years = Std.int(days / 356); |
| 31 |
var months = Std.int(days / 30.4167); // should be accurate enough |
| 32 |
var weeks = Std.int(days / 7); |
| 33 |
|
| 34 |
if (years == 0) { |
| 35 |
if (months < 2) { |
| 36 |
if (weeks < 1) { |
| 37 |
if (days == 0) return 'today'; |
| 38 |
if (days == 1) return '$days day ago'; |
| 39 |
return '$days days ago'; |
| 40 |
} else { |
| 41 |
if (weeks == 1) return '$weeks week ago'; |
| 42 |
else return '$weeks weeks ago'; |
| 43 |
} |
| 44 |
} else { |
| 45 |
return '$months months ago'; |
| 46 |
} |
| 47 |
} else { |
| 48 |
return years > 1 ? '$years years ago' : '$years year ago'; |
| 49 |
} |
| 50 |
} else { |
| 51 |
var month = _MONTHS[target.getMonth()]; |
| 52 |
var date = target.getDate(); |
| 53 |
var day = if (date < 10) '0$date' else '$date'; |
| 54 |
return '$day-$month ${target.getFullYear()}'; |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
public static function syntaxHighlightHTML(code:String):String { |
| 59 |
var html = code; |
| 60 |
html = ~/(("|')(.+?)?\2)/g.replace(html, "<span class=str>$1</span>"); |
| 61 |
html = ~/(<\\?)(.+?)(\/|\s|>)/g.replace(html, "$1<span class=kwd>$2</span>$3"); |
| 62 |
|
| 63 |
return html; |
| 64 |
} |
| 65 |
} |