diff --git a/src/main/scala/view/helpers.scala b/src/main/scala/view/helpers.scala index 78f658f..6bb1d0c 100644 --- a/src/main/scala/view/helpers.scala +++ b/src/main/scala/view/helpers.scala @@ -1,5 +1,5 @@ package view -import java.util.{Date, TimeZone} +import java.util.{Locale, Date, TimeZone} import java.text.SimpleDateFormat import play.twirl.api.Html import util.StringUtil @@ -15,6 +15,49 @@ */ def datetime(date: Date): String = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + val timeUnits = List( + (1000L, "second"), + (1000L * 60, "minute"), + (1000L * 60 * 60, "hour"), + (1000L * 60 * 60 * 24, "day"), + (1000L * 60 * 60 * 24 * 30, "month"), + (1000L * 60 * 60 * 24 * 365, "year") + ).reverse + + /** + * Format java.util.Date to "x {seconds/minutes/hours/days/months/years} ago" + */ + def datetimeAgo(date: Date): String = { + val duration = new Date().getTime - date.getTime + timeUnits.find(tuple => duration / tuple._1 > 0) match { + case Some((unitValue, unitString)) => + val value = duration / unitValue + s"${value} ${unitString}${if (value > 1) "s" else ""} ago" + case None => "just now" + } + } + + /** + * + * Format java.util.Date to "x {seconds/minutes/hours/days} ago" + * If duration over 1 month, format to "d MMM (yyyy)" + * + */ + def datetimeAgoRecentOnly(date: Date): String = { + val duration = new Date().getTime - date.getTime + val list = timeUnits.map(tuple => (duration / tuple._1, tuple._2)).filter(tuple => tuple._1 > 0) + if (list.isEmpty) + "just now" + else { + list.head match { + case (_, "month") => s"on ${new SimpleDateFormat("d MMM", Locale.ENGLISH).format(date)}" + case (_, "year") => s"on ${new SimpleDateFormat("d MMM yyyy", Locale.ENGLISH).format(date)}" + case (value, unitString) => s"${value} ${unitString}${if (value > 1) "s" else ""} ago" + } + } + } + + /** * Format java.util.Date to "yyyy-MM-dd'T'hh:mm:ss'Z'". */ diff --git a/src/main/twirl/account/repositories.scala.html b/src/main/twirl/account/repositories.scala.html index 1ad52df..8a3706b 100644 --- a/src/main/twirl/account/repositories.scala.html +++ b/src/main/twirl/account/repositories.scala.html @@ -25,7 +25,7 @@ @if(repository.repository.description.isDefined){
@pullreq.userName:@pullreq.branch
from @pullreq.requestUserName:@pullreq.requestBranch
- at @datetime(comment.registeredDate)
+ @helper.html.datetimeago(comment.registeredDate)
}.getOrElse {
Closed
@user(issue.openedUserName, styleClass="username strong") wants to merge @commits.size @plural(commits.size, "commit")
diff --git a/src/main/twirl/repo/blob.scala.html b/src/main/twirl/repo/blob.scala.html
index 2c895ac..68d3870 100644
--- a/src/main/twirl/repo/blob.scala.html
+++ b/src/main/twirl/repo/blob.scala.html
@@ -34,7 +34,7 @@
@Html(file.highlightText)