我在诸如Groovy JDK(GDK):File.deleteDir() , Groovy JDK(GDK):Text File to String , Groovy JDK( )的博客文章中查看了Groovy GDK对Java JDK的扩展中可用的一些非常有用的方法。 GDK):更多文件乐趣 , Groovy JDK(GDK):字符串支持 ,和Groovy JDK(GDK):编号支持 。 在本文中,我将介绍Groovy对Java JDK java.util.Date和java.util.Calendar类的GDK扩展的一些实用功能。
Java开发社区通常不喜欢 Java当前对日期和时间的标准支持。 我们中的许多人都期待JSR-310和/或已经使用Joda Time来解决Java处理日期和时间的缺点。
当第三方框架不可用或无法使用时,Groovy使日期和时间的使用变得更加容易.Groovy GDK Date扩展提供了几种新的且非常有用的方法,如其文档的屏幕快照所示。
我将在本文中重点介绍的这些有用方法包括: clearTime() , format(String) , getDateString() ,getTimeString(), parse(String,String) , parseToStringDate(String) , toCalendar() , toTimestamp()并更新(Map) 。 API中列出的许多其他方法都支持Groovy运算符重载 ,因此本文中未重点介绍。
Date.clearTime()和Calendar.clearTime()
有时候,人们只希望代表一个日期,而“ Date
或“ Calendar
的时间部分并不重要(这正是JSR 310将仅日期的构造(如LocalDate)引入JDK 8的原因。 在这种情况下,Groovy对Date
和Calendar
的扩展使轻松地“清除”时间部分成为可能。 下一个代码清单演示了Date.clearTime()
用法, Date.clearTime()
显示该代码已执行的屏幕快照。 请注意, clearTime()方法会将其作用的对象突变。
/**
* Demonstrates Groovy's GDK Date.clearTime() method. Note that the clearTime()
* method acts upon the Date object upon which it is called, mutating its value
* in addition to returning a reference to that changed object.
*/
def demoClearTime()
{
printTitle('Groovy GDK Date.clearTime()')
def now = new Date()
println 'Now: ${now}'
def timelessNow = now.clearTime()
println 'Now sans Time: ${timelessNow}'
println 'Mutated Time: ${now}'
}
Calendar
的clearTime()的工作方式与下一个代码片段及其执行过程的随附屏幕快照所示相似。
/**
* Demonstrates Groovy's GDK Calendar.clearTime() method. Note that the
* clearTime() method acts upon the Calendar object upon which it is called,
* mutating its value in addition to returning a reference to that changed object.
*/
def demoCalendarClearTime()
{
printTitle('Groovy GDK Calendar.clearTime()')
def now = Calendar.getInstance()
println 'Now: ${now}'
now.clearTime()
println 'Now is Timeless: ${now}'
}
Date.format和Calendar.format
在Java开发中,通常需要以特定的用户友好格式显示Date
或Calendar
,这通常使用SimpleDateFormat实例来完成。 Groovy使用相应的Date.format(String)和Calendar.format(String)方法简化了将格式应用于Date
或String
过程。 接下来显示了展示每个代码的代码清单,每个代码清单后面是显示执行代码的屏幕快照。
/**
* Demonstrate how much more easily a formatted String representation of a Date
* can be acquired in Groovy using GDK Date.format(String). No need for an
* explicit instance of SimpleDateFormat or any other DateFormat implementation
* here!
*/
def demoFormat()
{
printTitle('Groovy GDK Date.format(String)')
def now = new Date()
println 'Now: ${now}'
def dateString = now.format('yyyy-MMM-dd HH:mm:ss a')
println 'Formatted Now: ${dateString}'
}
/**
* Demonstrate how much more easily a formatted String representation of a
* Calendar can be acquired in Groovy using GDK Calendar.format(String). No need
* for an explicit instance of SimpleDateFormat or any other DateFormat
* implementation here!
*/
def demoCalendarFormat()
{
printTitle('Groovy GDK Calendar.format(String)')
def now = Calendar.getInstance()
println 'Now: ${now}'
def calendarString = now.format('yyyy-MMM-dd HH:mm:ss a')
println 'Formatted Now: ${calendarString}'
}
Date.getDateString(),Date.getTimeString()和Date.getDateTimeString()
前面显示的format
方法允许自定义表示Date
或Calendar
,而clearTime
方法可以显示time元素从Date
或Calendar
实例中删除。 Groovy在Date
上提供了一些便利的方法,用于仅显示用户友好的日期,仅时间或日期和时间,而无需指定格式或清除时间部分。 这些方法以DateFormat.SHORT (用于日期部分)和DateFormat.MEDIUM (用于时间部分)指定的预定义格式打印日期和时间。 接下来显示每种方法的代码清单,每个代码清单之后是正在执行的代码的屏幕快照。
/**
* Demonstrates Groovy's GDK Date.getDateString() method. Note that this
* method doesn't change the underlying date, but simply presents only the date
* portion (no time portion is presented) using the JDK's DateFormat.SHORT
* constant (which defines the locale-specific 'short style pattern' for
* formatting a Date).
*/
def demoGetDateString()
{
printTitle('Groovy GDK Date.getDateString()')
def now = new Date()
println 'Now: ${now}'
println 'Date Only: ${now.getDateString()}'
println 'Now Unchanged: ${now}'
}
/**
* Demonstrates Groovy's GDK Date.getTimeString() method. Note that this
* method doesn't change the underlying date, but simply presents only the time
* portion (no date portion is presented) using the JDK's DateFormat.MEDIUM
* constant (which defines the locale-specific 'medium style pattern' for
* formatting a Date).
*/
def demoGetTimeString()
{
printTitle('Groovy GDK Date.getTimeString()')
def now = new Date()
println 'Now: ${now}'
println 'Time Only: ${now.getTimeString()}'
println 'Now Unchanged: ${now}'
}
/**
* Demonstrates Groovy's GDK Date.getDateTimeString() method. Note that this
* method doesn't change the underlying date, but simply presents the date and
* time portions as a String. The date is presented with locale-specific format
* as defined by DateFormat.SHORT and the time is presented with locale-specific
* format as defined by DateFormat.MEDIUM.
*/
def demoGetDateTimeString()
{
printTitle('Groovy GDK Date.getDateTimeString()')
def now = new Date()
println 'Now: ${now}'
println 'Date/Time String: ${now.getDateTimeString()}'
println 'Now Unchanged: ${now}'
}
Date.parse(字符串,字符串)
GDK Date
类提供了Date.parse(String,String)方法,这是一个“便捷方法”,“充当SimpleDateFormat的包装器”。 下面的代码段和相应的代码快照显示了该方法的有效性。
/**
* Demonstrate Groovy GDK's Date.parse(String, String) method which parses a
* String (second parameter) based on its provided format (first parameter).
*/
def demoParse()
{
printTitle('Groovy GDK Date.parse(String, String)')
def nowString = '2012-Nov-26 11:45:23 PM'
println 'Now String: ${nowString}'
def now = Date.parse('yyyy-MMM-dd hh:mm:ss a', nowString)
println 'Now from String: ${now}'
}
Date.parseToStringDate(String)
GDK Date.parseToStringDate(String)方法可用于从与Date.toString()
方法提出的确切格式匹配的String
获取Date
的实例。 换句话说,此方法对于从Date
的toString()
方法生成的String
转换回Date
很有用。
下面的代码段和相应输出的屏幕快照演示了此方法的使用。
/**
* Demonstrate Groovy GDK's Date.parseToStringDate(String) method which parses
* a String generated by a Date.toString() call, but assuming U.S. locale to
* do this.
*/
def demoParseToStringDate()
{
printTitle('Groovy GDK Date.parseToStringDate(String)')
def now = new Date()
println 'Now: ${now}'
def nowString = now.toString()
def nowAgain = Date.parseToStringDate(nowString)
println 'From toString: ${nowAgain}'
}
GDK Date.parseToStringDate(String)
方法有一个潜在的重大缺点。 正如其文档所述,它仅依赖于“美国语言环境常量”。
Date.toCalendar()和Date.toTimestamp()
将java.util.Date转换为java.util.Calendar或java.sql.Timestamp通常很有用。 Groovy使用GDK Date提供的方法Date.toCalendar和Date.toTimestamp()使这些普通转换特别容易。 以下代码片段中演示了这些内容,其输出显示在相应的屏幕快照中。
/**
* Demonstrates how easy it is to get a Calendar instance from a Date instance
* using Groovy's GDK Date.toCalendar() method.
*/
def demoToCalendar()
{
printTitle('Groovy GDK Date.toCalendar()')
def now = new Date()
println 'Now: ${now}'
def calendarNow = now.toCalendar()
println 'Now: ${calendarNow} [${calendarNow.class}]'
}
/**
* Demonstrates how easy it is to get a Timestamp instance from a Date instance
* using Groovy's GDK Date.toTimestamp() method.
*/
def demoToTimestamp()
{
printTitle('Groovy GDK Date.toTimestamp()')
def now = new Date()
println 'Now: ${now}'
def timestampNow = now.toTimestamp()
println 'Now: ${timestampNow} [${timestampNow.class}]'
}
Date.updated(地图)[和Calendar.updated(地图)]
我将在本文中讨论的GDK Date
提供的最后一种便捷方法是Date.updated(Map) ,其文档描述为'支持创建一个具有与现有Date相似的属性的新Date(保持不变)。但某些字段会根据变化图进行更新。” 换句话说,此方法允许一个以某个Date
实例开始并获取另一个具有与提供的Map
指定的更改不同的属性的Date
实例。
下一个代码清单从现有的Date
实例获取一个新的Date
实例,并使用Date.updated(Map)
方法更新了几个字段。 代码清单后是其执行的屏幕快照。
/**
* Demonstrate Groovy GDK's Date.updated(Map) with adaptation of the example
* provided for that method in that method's Javadoc-based GDK documentation.
* Note that the original Date upon which updated is invoked is NOT mutated and
* the updates are on the returned instance of Date only.
*/
def demoUpdated()
{
printTitle('Groovy GDK Date.updated(Map)')
def now = new Date()
def nextYear = now[YEAR] + 1
def nextDate = now[DATE] + 1
def prevMonth = now[MONTH] - 1
def oneYearFromNow = now.updated(year: nextYear, date: nextDate, month: prevMonth)
println 'Now: ${now}'
println '1 Year from Now: ${oneYearFromNow}'
}
该演示表明原始的Date
实例确实保持不变,并且提供了具有指定字段更改的副本。 GDK Calendar
还有一个等效项,称为Calendar.updated(Map) 。
结论
我喜欢Groovy的一件事是SDK类的GDK扩展。 在本文中,我研究了JDK Date的GDK Date扩展如何提供许多有用的便捷方法,这些方法可以使代码更简洁和可读性更好。
参考: Groovy JDK(GDK): JCG合作伙伴 Dustin Marx在“ 实际事件的启发”博客上的日期和日历 。
翻译自: https://www.javacodegeeks.com/2012/12/groovy-jdk-gdk-date-and-calendar.html