Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Date from timestamp in Groovy

As trivial as it may seem, I cannot find a way to transform a Unix timestamp into a Date object in Groovy.

Let me try with 1280512800, which should become Fri, 30 Jul 2010 18:00:00 GMT

My first attempt was

new Date(1280512800)
// wrong, becomes Thu Jan 15 20:41:52 CET 1970

Then I read that Java timestamps use milliseconds, hence I should use

new Date((long)1280512800 * 1000)
// the cast to long is irrelevant in Groovy, in any case I get
// Thu Jan 08 03:09:05 CET 1970

What is the right way to convert a timestamp to a Date? What if I want to specify the timezone to work in?

like image 884
Andrea Avatar asked Jul 12 '12 09:07

Andrea


People also ask

How do you get the day on Groovy?

You can use this to output a three character representation of the name of the week day: theDate = "2017-10-09T00:00:00.000"; def parsedDate = new Date(). parse("yyyy-MM-dd'T'HH:mm:ss. SSS", theDate); def day = new java.

How do I get yesterday's date on Groovy?

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?

The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below.

How do I convert a date to a string in Groovy?

String newDate = Date. parse('MM/dd/yyyy',dt). format("yyyy-MM-dd'T'HH:mm:ss'Z'");


1 Answers

The problem is it's going with Integers, then the multiplication is causing truncation...

Try:

new Date( 1280512800L * 1000 )

or

new Date( ((long)1280512800) * 1000 )
like image 164
tim_yates Avatar answered Oct 06 '22 00:10

tim_yates