简体   繁体   中英

Perl one liner command to convert EST time to GMT time

I am trying to build a one line command in Perl to convert an EST datetime to GMT time and print the result. I'm using the module "DateTime" to accomplish this.

The command I tried is:

perl -MDateTime=set_Time_Zone -e "DateTime->new(year=>2019,month=>5,day=>10,hour=>18,minute=>40,time_zone=>EST)" -e "$dt->set_time_zone(GMT)"

The error it's throwing is

Can't call method "set_time_zone" on an undefined value at -e line 2.

How to call a method and print the hour in GMT?

Four problems:

  1. DateTime doesn't export set_Time_Zone .
  2. You use $dt without ever giving it a value. (This is what produces the error message.)
  3. "EST" is not a standard time zone name, and should be avoided. It could refer to Eastern Standard Time (UTC-0500), a time zone that's mostly unused on May 10th. If so, specify -0500 instead.
  4. You don't print anything.

If you really did mean Eastern Standard Time (despite it not being used on May 10th in places that observe DST), use the following:

perl -MDateTime -le'print DateTime->new(...,time_zone=>"-0500")->set_time_zone("UTC")'

It's far more likely that you meant Eastern Daylight Time. If so, use the following:

perl -MDateTime -le'print DateTime->new(...,time_zone=>"-0400")->set_time_zone("UTC")'

Instead of using fixed offsets, you can specify the geographically-based names from the tz database. When using these, DateTime factors in whether DST is used on the date-time in question and uses the appropriate offset. This is done as follows:

perl -MDateTime -le'print DateTime->new(...,time_zone=>"America/New_York")->set_time_zone("UTC")'

Finally, the following is how you'd tell DateTime to use the local time zone:

perl -MDateTime -le'print DateTime->new(...,time_zone=>"local")->set_time_zone("UTC")'

Notes:

  • If you want a different output format, you can use ->strftime(...) .
  • If using the Windows command shell, swap ' and " .

Where do you think $dt is set? And how is it gonna print without a print() ? Try:

perl -MDateTime=set_Time_Zone -e "print(DateTime->new(year=>2019,month=>5,day=>10,hour=>18,minute=>40,time_zone=>EST)->set_time_zone(GMT));"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM