该笔记将记录:在 Apache Groovy 中,与时间有关的常用操作。
Patterns for Formatting and Parsing
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns
Predefined Formatters
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined
常用转义字符
println new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") println new Date().format("yyyy-MM-dd'T'HH:mm:ssXXX") // 通过 '' 针对字符转义
Timestamp to Date String
soapui – Convert milliseconds to yyyy-MM-dd date-time format in Groovy – Stack Overflow
def timestamp = Long.valueOf("1726244425") print new Date( timestamp * 1000 ).format("yyyyMMdd.HHmmss.SSS")
String => Date(“万能方法”)
很多时候,我们使用的日期格式比较随意,因此需要告诉 Parser 我们的日期格式:
def input = '2021-03-23T19:46:22+08:00' def pattern = "yyyy-MM-dd'T'HH:mm:ssX" def date = Date.parse(pattern, input) assert date.toString() == 'Tue Mar 23 19:46:22 CST 2021' // T:因为这里 T 是普通字符,所以需要使用 ' 进行转义处理 // X:ISO 8601 time zone,参考 Java 7 / java.text.SimpleDateFormat 文档。
将时间增加若干长度(e.g. currentDate + 5 seconds)
import groovy.time.TimeCategory currentDate = new Date() use( TimeCategory ) { after30Mins = currentDate + 5.seconds }
判断 | 时间是否在某范围内
public Boolean nowBetween(String beg, String end, String format = "HH:mm") { def timeBeg = new SimpleDateFormat(format).parse(beg); def timeEnd = new SimpleDateFormat(format).parse(end); def timeRange = timeBeg..timeEnd; def timeNow = new SimpleDateFormat(format).format(new Date()); def time = new SimpleDateFormat(format).parse(timeNow); return timeRange.containsWithinBounds(time); }
判断 | 时间是否为几天之前
def now = new Date() def target = Date.parse('yyy-MM-dd HH:mm:ss Z', "xxxxxxx") assert now - target > 7 def daysbefore = new Date() - 7 def target = Date.parse("yyy-MM-dd HH:mm:ss Z","2024-09-1 07:42:03 +0800 CST") assert target < daysbefore
参考文献
DateTimeExtensions (Groovy 3.0.6)
SimpleDateFormat (Java Platform SE 7 )
date – Java SimpleDateFormat for time zone with a colon separator? – Stack Overflow
查 | 查询日期
Groovy – Dates & Times – Tutorialspoint
after(), equals(), before(), compareTo(), …
WIP
改 | 修改日期
datetime – Incrementing date object by hours/minutes in Groovy – Stack Overflow
previous(), next(), …
java – Subtract a date by 1 or 2 in groovy – Stack Overflow
WIP