Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 756
Cornelius Qualley Avatar asked Jun 07 '13 02:06

Cornelius Qualley


People also ask

How do I change the date format in groovy?

If you wish to change from the default date formatting you can append a . format() to function and pass it a string paramater.

How do I get today's date on Groovy?

Date previousDate = new Date() Date currentDate = new Date() previousDate. upto(currentDate) { it -> it-> represents date object. } currentDate. downto(previousDate) { it -> it-> represents date object. }

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.


3 Answers

You should generally never change the default time zone just for your local benefits, as that affects all the code in JVM - it may want the actual local time zone to be the default, for example. Hence, using TimeZone.setDefault() is a bad practice unless you are sure that all your code will want that time zone and that all code is yours and that this will never change. That is a lot to ask.

Instead you should explicitly specify the time zone of interest in your calls.

  • If you want to use a date/time format that is specific to the locale of the user/machine, you should use the DateFormat factory, specifically one of the following static methods - they will take care of complex locale/language specifics not possible using any other approach (including SimpleDateFormatter):

  • getDateTimeInstance() - for the default locale and default styles.

  • getDateTimeInstance(int dateStyle, int timeStyle) for the default locale and specified styles
  • getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) for specified styles and locale

Once you get that DateFormatter instance you will want to call the setTimeZone(TimeZone.getTimeZone('UTC')) on it. That will make that formatter use that time zone. You can also use any other time zone.

Finally, you will call the dateFormat.format(Date date) method to get a String representation of that date, in the locale, style and time zone of choice.

If you do NOT want locale specific format but want to fix to something of your own, such as ISO, instead of creating the DateFormat instance using a static factory method described above, you will want to use the SimpleDateFormat instead. Specifically you will use the new SimpleDateFormat(String pattern) constructor. The pattern would be following the definitions in the SimpleDateFormat JavaDoc, and could be 'yyyy-MM-dd HH:mm:ss.SSS', for example.

You would then call the setTimeZone() method on that SimpleDateFormat instance the same was as for (any) DateFormat. In Groovy you can skip the explicit SimpleDateFormat creation and you can instead use the Groovy Date enhancement, its format(String format, TimeZone tz) method - it will do the SimpleDateFormat stuff under the covers.

Locale-specific format approach example (Java and/or Groovy):

String gimmeUTC(Date date, Locale locale) {
  DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
  dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
  return dateFormat.format(date);
}

Fixed format approach example (Java and/or Groovy):

String gimmeUTC(Date date, Locale locale) {
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
  return dateFormat.format(date);
}

Fixed format example (Groovy only):

String gimmeUTC(Date date) {
  return date.format('yyyy-MM-dd HH:mm:ss.SSS', TimeZone.getTimeZone('UTC'));
}
like image 166
Learner Avatar answered Nov 07 '22 15:11

Learner


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.

like image 41
dmahapatro Avatar answered Nov 07 '22 13:11

dmahapatro


tl;dr

Java syntax here, but you can call java.time classes in Groovy too.

Instant.now()
       .toString()

2017-01-23T01:23:45.987654321Z

Avoid legacy classes

The Question and other Answers use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

Apparently you want to generate a String in standard ISO 8601 format representing a date-time value in UTC time zone.

The java.time.Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.now() ;

The java.time classes use ISO 8691 formats by default when parsing/generating strings.

String output = instant.toString() ;

2017-01-23T01:23:45.987654321Z

If you want whole seconds, without a fraction, truncate.

Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS ) ;
like image 23
Basil Bourque Avatar answered Nov 07 '22 14:11

Basil Bourque