Search code examples
datetimegroovysoapuimilliseconds

Convert specific datetime to milliseconds in groovy


I am trying to convert specific datetime to millisecond. Then i have to add 15min to the milliseconds. Both the output needs in milliseconds.

TimeZone.setDefault(TimeZone.getTimeZone('UTC'))
d = "21/09/2020"
t = "03:00"
Date unixTimedate = new Date("$d $t:00");
long fromTime = unixTimedate.getTime()
log.info fromTime

def c = new Date(fromTime).format("dd/MM/yyyy'T'HH:mm:ss");
log.info c
d =  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(c)
use(TimeCategory)
{
    def startdate2 = d + 15.minutes
    log.info "updated datetime" + startdate2
    def outputDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    def newstartdatetime = "${startdate2.format(outputDateFormat)}"
    log.info "StartDateTime : " + newstartdatetime
long toTime = newstartdatetime.getTime()
log.info toTime
}

Output: Mon Sep 21 08:17:17 UTC 2020:INFO:1631156400000 which is Thu Sep 09 2021 03:00:00

21 now converted to 09


Solution

  • If you are using JDK 8+ then you can use the Date and Time classes, which are inspired by the fabulous Joda-Time library.

    Consider:

    import java.time.*
    import java.time.format.DateTimeFormatter
    import java.util.concurrent.TimeUnit
    
    def formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy'T'HH:mm:ss")
    def text1 = "21/09/2020T03:00:00"
    
    def dateTime1 = LocalDateTime.parse(text1, formatter)
    def zonedDateTime1 = dateTime1.atZone(ZoneId.of("UTC"))
    long milliValue1 = zonedDateTime1.toInstant().toEpochMilli()
    
    def intervalInSeconds = TimeUnit.MINUTES.toSeconds(15)
    def milliValue2 = zonedDateTime1.toInstant()
                                  .plusSeconds(intervalInSeconds)
                                  .toEpochMilli()
    def dateTime2 = LocalDateTime.ofInstant(
                        Instant.ofEpochMilli(milliValue2), ZoneId.of("UTC"))
    def text2 = dateTime2.format(formatter)
    
    println "milliValue1  : " + milliValue1 
    println "text1        : " + text1
    
    println "milliValue2  : " + milliValue2 
    println "text2        : " + text2
    

    Output:

    milliValue1  : 1600657200000
    text1        : 21/09/2020T03:00:00
    milliValue2  : 1600658100000
    text2        : 21/09/2020T03:15:00