Hary
Hary

Reputation: 5818

Groovy DateTime Format unexpected output

The below code doesn't return the expected output. What's wrong with it?

def a = new Test(new Date());

println a.getLogFormatDate()

class Test
{
    String _dateTime;
    static final String _logDateFormat = "E MMM dd HH:mm:ss zzz yyyy";
    static final String _timeZoneUTC = "UTC";

    Test(Date dateTime)
    {
        _dateTime = dateTime;
    }

    public String getLogFormatDate()
     {
        return _dateTime.format(_logDateFormat, TimeZone.getTimeZone(_timeZoneUTC));
     }
}​

Expected Output:

Mon Nov 12 14:10:46 UTC 2018

Actual Output:

E MMM dd HH:mm:ss zzz yyyy

Upvotes: 0

Views: 46

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

You have defined _dateTime class field with type String, so your getLogFormatDate calls

String.format("E MMM dd HH:mm:ss zzz yyyy", TimeZone.getTimeZone("UTC"))

while you expect

Date.format("E MMM dd HH:mm:ss zzz yyyy", TimeZone.getTimeZone("UTC"))

to be called.

Define _dateTime field as Date and it will works as you expect.

Upvotes: 1

Related Questions