Created
March 28, 2016 19:57
-
-
Save thorntonrose/b9404c4a7f17ced2e807 to your computer and use it in GitHub Desktop.
Date utility methods
This file contains 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
import java.text.* | |
class Dates { | |
static final DATE_TIME = "yyyy-MM-dd HH:mm:ss" | |
static final EUROPEAN = "dd/MM/yyyy" | |
static final HSQLDB = "yyyy-MM-dd HH:mm:ss.SSS" | |
static final ISO = "yyyy-MM-dd'T'HH:mm:ss.SSS" | |
static final YEAR_MONTH_DAY = "yyyy-MM-dd" | |
static final YEAR_MONTH_DAY_HOUR_MINUTE = "yyyy-MM-dd (HH:mm)" | |
static final MONTH_DAY_YEAR = "MM/dd/yyyy" | |
static final WEEKDAY_SHORT = "EEE" | |
static final WEEK = "w" | |
static final WEEK_YEAR = "ww-YY" | |
static def getLastMonday(final date){ | |
def day = new Date().parse(YEAR_MONTH_DAY, date) | |
day.clearTime() | |
format(day - day.calendarDate.dayOfWeek + 2, YEAR_MONTH_DAY) | |
} | |
static def format(date, pattern = ISO) { | |
date ? date.format(pattern) : "" | |
} | |
static def parse(text, pattern = ISO) { | |
text ? Date.parse(pattern, text) : null | |
} | |
static def timestamp(date = null) { | |
date ? new java.sql.Timestamp(date.time) : new java.sql.Timestamp(System.currentTimeMillis()) | |
} | |
static def isDay(date, day) { | |
format(WEEKDAY_SHORT, date) == day | |
} | |
static def isWeekday(String day) { | |
(day != "Sat") && (day != "Sun") | |
} | |
static def isWeekday(Date date) { | |
isWeekday(format(date, WEEKDAY_SHORT)) | |
} | |
static def isMonday(String day) { | |
(day == "Mon") | |
} | |
static def isMonday(Date date) { | |
isMonday(format(date, WEEKDAY_SHORT)) | |
} | |
static def getMondays(startDate, endDate, pattern = null) { | |
def mondays = (startDate .. endDate).findAll { isMonday(it) } | |
pattern ? mondays.collect { format(it, pattern) } : mondays | |
} | |
static def getWeekdays(startDate, endDate, pattern = null) { | |
def weekdays = (startDate .. endDate).findAll { isWeekday(it) } | |
pattern ? weekdays.collect { format(it, pattern) } : weekdays | |
} | |
static def getMinSec(startTime) { | |
def duration = (System.currentTimeMillis() - startTime) / 1000 | |
def min = (int) (duration / 60) | |
def sec = duration - (min * 60) | |
"$min min, $sec sec" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment