Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: How do you initialise and compare date/time values from different timezones?

I need to standardise and compare date/time fields that are in differnt timezones. eg How do you find the time difference between the following two times?...

"18-05-2012 09:29:41 +0800"
"18-05-2012 09:29:21 +0900"

What's the best way to initialise standard varaibles with the date/time? The output needs to display the difference and normalised data in a timezone (eg +0100) that is different to the incoming values and different to the local environment.

Expected Output:

18-05-2012 02:29:41 +0100 
18-05-2012 01:29:21 +0100
Difference: 01:00:20
like image 336
Chris Avatar asked Dec 16 '22 23:12

Chris


2 Answers

import java.text.SimpleDateFormat

def dates = ["18-05-2012 09:29:41 +0800",
 "18-05-2012 09:29:21 +0900"].collect{
   new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z").parse(it)
}
def dayDiffFormatter = new SimpleDateFormat("HH:mm:ss")
dayDiffFormatter.setTimeZone(TimeZone.getTimeZone("UTC"))
println dates[0]
println dates[1]
println "Difference "+dayDiffFormatter.format(new Date(dates[0].time-dates[1].time))

wow. doesn't look readable, does it?

like image 158
rdmueller Avatar answered May 23 '23 08:05

rdmueller


Or, use the JodaTime package

@Grab( 'joda-time:joda-time:2.1' )
import org.joda.time.*
import org.joda.time.format.*

String a = "18-05-2012 09:29:41 +0800"
String b = "18-05-2012 09:29:21 +0900"

DateTimeFormatter dtf = DateTimeFormat.forPattern( "dd-MM-yyyy HH:mm:ss Z" );

def start = dtf.parseDateTime( a )
def end = dtf.parseDateTime( b )

assert 1 == Hours.hoursBetween( end, start ).hours
like image 40
tim_yates Avatar answered May 23 '23 09:05

tim_yates