Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new Date in Groovy at specific date and time

Tags:

date

groovy

I wonder if there is other way how to create new Date in Groovy at specific date and time than parse it from String with Date.parse method. Can I get complete list of Date creation in Groovy?

like image 624
michal.kreuzman Avatar asked Apr 03 '14 20:04

michal.kreuzman


People also ask

How do I set the date in groovy?

Date Formatting In Groovy, you can use format function to format date object. You can see a quick example below. In this example, we simply parsed the date string into a date object on line 08 , and then we have formatted that date object by using format function on line 09 .

How do you get the next date on Groovy?

currentDate. downto(previousDate) { it -> it-> represents date object. } minus: Subtract number of days from given date & will return you new date. plus: Add number of dayes to date object & it will give you new date.

Which class in groovy specifies the instant date and time?

Groovy Programming Fundamentals for Java Developers The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below.


1 Answers

You can use the existing Java methods to create a date:

// takes the date encoded as milliseconds since midnight, January 1, 1970 UTC def mydate = new Date(System.currentTimeMillis())  // create from an existing Calendar object def mydate = new GregorianCalendar(2014, Calendar.APRIL, 3, 1, 23, 45).time 

Groovy also provides some streamlined extensions for creating Dates. Date.parse() and Date.parseToStringDate() parse it from a String. The Date.copyWith() method builds a date from a map. You can use them like this:

// uses the format strings from Java's SimpleDateFormat def mydate = Date.parse("yyyy-MM-dd hh:mm:ss", "2014-04-03 1:23:45")  // uses a format equivalent to EEE MMM dd HH:mm:ss zzz yyyy def mydate = Date.parseToStringDate("Thu Apr 03 01:23:45 UTC 2014")  def mydate = new Date().copyWith(     year: 2014,      month: Calendar.APRIL,      dayOfMonth: 3,      hourOfDay: 1,     minute: 23,     second: 45) 
like image 186
ataylor Avatar answered Nov 24 '22 00:11

ataylor