sbolla
sbolla

Reputation: 711

Append a Z at the end of the UTC time

I am using perl, and passing this -->

DateTime->now( time_zone => 'UTC' )) to the method below

and

sub get_datetime{
    my ($datetime) = @_;
    my $formatter = new DateTime::Format::Strptime(pattern => "%Y-%m-%d %H:%M:%S",
                       time_zone => "UTC");
    return $formatter->format_datetime($datetime);
}

and I want to display the time like 2012-10-10 10:00:01Z

how can I append the Z at the end for the UTC times? I tried pattern => "%Y-%m-%d %H:%M:%S%Z" but thats not compiling.

Upvotes: 0

Views: 538

Answers (2)

Dave Cross
Dave Cross

Reputation: 69314

I'm surprised that %Z stops your code from compiling. What error message do you get?

%Z is the correct format to use to get the timezone, but it will display in a different format to the one you want.

$ perl -MDateTime -E'say DateTime->now->strftime("%Y-%m-%d %H:%M:%S%Z")'
2012-11-02 13:56:05UTC

Another option is to use %z. But again, that doesn't give the format you want.

$ perl -MDateTime -E'say DateTime->now->strftime("%Y-%m-%d %H:%M:%S%z")'
2012-11-02 13:57:00+0000

So, yes, it looks like hard-coding the 'Z' is your best option. But it makes me slightly uncomfortable as how can you be sure that your date actually is in UTC?

$ perl -MDateTime -E'say DateTime->now->set_time_zone("America/New_York")->strftime("%Y-%m-%d %H:%M:%SZ")'
2012-11-02 10:01:56Z

Upvotes: 0

ysth
ysth

Reputation: 98398

Try:

pattern => "%Y-%m-%d %H:%M:%SZ"

The %-letter parts are what gets replaced by things from the time; a literal Z shouldn't have a % before it.

Upvotes: 1

Related Questions