Hello Guys,
Recently working on one of my projects, I have to calculate the time difference between two dates and display on the UI. Although there are various ways to achieve this, but to make sure that it can also be reusable, I have decided to create the grails taglib to achieve the same functionality. Below are the steps to follow.
1- Create a taglib in your project
1 |
grails create-taglib [name] |
grails create tag-lib com.dm.DateExampleTagLib
2- Use the following code to calculate time in minutes/hours/days.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
class DateExampleTagLib { static namespace = "DateTag" def dateFromNow = { attrs -> def date = attrs.date def niceDate = getNiceDate(date) out << niceDate } String getNiceDate(Date date) { def now = new Date() def diff = Math.abs(now.time - date.time) long second = 1000 long minute = second * 60 long hour = minute * 60 long day = hour * 24 def niceTime = "" long calc = 0; calc = Math.floor(diff / day) if (calc) { niceTime += calc + " day" + (calc > 1 ? "s " : " ") diff %= day } calc = Math.floor(diff / hour) if (calc) { niceTime += calc + " hour" + (calc > 1 ? "s " : " ") diff %= hour } calc = Math.floor(diff / minute) if (calc) { niceTime += calc + " minute" + (calc > 1 ? "s " : " ") diff %= minute } if (!niceTime) { niceTime = "Right now" } else { niceTime += (date.time > now.time) ? "from now" : "ago" } return niceTime } static defaultEncodeAs = [taglib:'html'] } |
3) The above tag can be used on the UI in following way.
<DateTag:dateFromNow date=”${emp.createdDate}”></DateTag:dateFromNow>
Snap Shot:
Recent Comments