Cornelius Qualley Cornelius Qualley - 1 year ago 125
Groovy Question

Groovy UTC date formatting

Okay, so I'm doing a simple UTC date formatting script which takes UTC and converts it in to a specific format for date and time. I can get the script to work fine in javascript, but the plugin I'm using requires Groovy apparently. I'm not familiar with it, I've been told that the programming is essentially the same as it can use javascript libraries/language. In any case, here is my code snippet:

import java.util.*;

var d = new Date();
var CurrentDay = ('0' + d.getUTCDate()).slice(-2);
var CurrentMonth = ('0' + d.getUTCMonth()).slice(-2);
var CurrentYear = d.getUTCFullYear();
var CurrentHours = ('0' + d.getUTCHours()).slice(-2);
var CurrentMinutes = ('0' + d.getUTCMinutes()).slice(-2);
var CurrentSeconds = ('0' + d.getUTCSeconds()).slice(-2);
var DateFormatted = CurrentYear.toString() + CurrentMonth.toString() + CurrentDay.toString() + CurrentHours.toString() + CurrentMinutes.toString() + CurrentSeconds.toString();
return DateFormatted;


I'm getting this error message back when I attempt to run my script:

groovy.lang.MissingMethodException: No signature of method: Script1.var() is applicable for argument types: (java.util.Date) values: [Thu Jun 06 21:18:43 CDT 2013]
Possible solutions: wait(), run(), run(), every(), any(), wait(long)
Parameters:
{}


Any help would be much appreciated. Also, I can get this script to run exactly as I would like as a normal javascript.

Answer Source

The equivalent of var from JavaScript is "def" in Groovy. Moreover, setting up a date format is easier in Groovy using Groovy Date:

TimeZone.setDefault(TimeZone.getTimeZone('UTC'))
def now = new Date()
println now
println now.format("MM/dd/yyyy'T'HH:mm:ss.SSS'Z'")


//Prints:
Fri Jun 07 02:57:58 UTC 2013
06/07/2013T02:57:58.737Z

You can modify the format according to your need. For available formats refer SimpleDateFormat.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download