rsram312
rsram312

Reputation: 141

Groovy - Compare date and Time

I have two strings , which are each got from respective shell commands and are not uniformly formatted. Two strings obtained are as follows:

Date : Tue Feb 28 16:23:20 2017 -0600
Executed at : Tue Feb 28 17:24:06 EST 2017 

EDIT: I get the above mentioned dates , one through git log and other through cat and store both in variables

First date is got through and stored in X:

  sh 'git log <file> | grep Date | head -n 1 > X '

Second date is got through below and stored in Y:

   sh 'cat chef-policy-release.log | grep <file> | tail -n 1 | grep -o "Executed at.*" > Y' 

Now I wanted to pick out just date and time among that and wanted to check if executed time is after the Date value or not ?

Upvotes: 1

Views: 9608

Answers (2)

Rao
Rao

Reputation: 21389

Here you go.

def dateStr1 = 'Tue Feb 28 16:23:20 2017 -0600'
def dateStr2 = 'Tue Feb 28 17:24:06 EST 2017'
def pattern1 = "EEE MMM dd HH:mm:ss yyyy Z"
def pattern2 = "EEE MMM dd HH:mm:ss z yyyy"
def date = new Date().parse(pattern1, dateStr1)
def executeDate = new Date().parse(pattern2, dateStr2)
assert date < executeDate, 'Execute Date is earlier than the date'

You may quickly try it online (negative test)Demo

EDIT: Based on OP's comment to parse the string and extract the date
You could have applied @GreBeardedGeek's parsing logic.

//Closure to get the date parsed
def getDate = { delimiter, dateFormat, dateStr  ->
   def dt = dateStr.substring(dateStr.indexOf(delimiter) + 1).trim()
   println dt
   new Date().parse(dateFormat, dt)
}

def dateStr1 = 'Date : Tue Feb 28 16:23:20 2017 -0600'
def dateStr2 = 'Executed at : Tue Feb 28 17:24:06 EST 2017'
def pattern1 = "EEE MMM dd HH:mm:ss yyyy Z"
def pattern2 = "EEE MMM dd HH:mm:ss z yyyy"
def date = getDate(':', pattern1, dateStr1)
def executeDate = getDate(':', pattern2, dateStr2)
assert date < executeDate, 'Execute Date is earlier than the date'

Edit#2​ can be more simplified to:

//Set / assign the two dates
def dateStr1 = 'Date : Tue Feb 28 16:23:20 2017 -0600'
def dateStr2 = 'Executed at : Tue Feb 28 17:24:06 EST 2017'
def getDate = { dateStr  -> Date.parse(dateStr.substring(dateStr.indexOf(':') + 1).trim()) }
assert getDate(dateStr1) < getDate(dateStr2), 'Execute Date is earlier than the date'

Upvotes: 0

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Similar to Rao's answer, but with a function to parse the string, no need for date format strings, and without creating un-needed Date instances:

class DateTest{
  public static void main(String[] args) {
    String logDateString = args[0];
    String execDateString = args[1];

    Date logDate = parseDate(logDateString);
    Date execDate = parseDate(execDateString);

    System.out.println(execDate > logDate);
  }

  static def parseDate(String rawString) {
    String dateString = rawString.substring(rawString.indexOf(":") + 1).trim();
    new Date(Date.parse(dateString));
  }
}

Upvotes: 1

Related Questions