How to display 4/25/10 to 2010-25-04?

2020-04-21 01:39发布

my$str= '4/25/10';
my$sr = join(' ',split (/\//,$str));
#my$s = sprintf '%3$d %2$d %1$d',$srt;
print$sr,"\n";

output:

4 25 10

But i want output like 2010-25-04.Can any one suggest me how display the my desire output.Give me your suggestion you answers will be appreciable.

4条回答
萌系小妹纸
2楼-- · 2020-04-21 01:47

Well, a braindead solution might be:

my @date = split( /\//,$str)
printf("%04d-%02d-%02d", $date[2] + 2000, $date[1], $date[0]);

You could write something a little more self-documenting by highlighting what you expect to be year, month and day like so:

my ($day, $month, $year) = split /\//, $str;
printf("%04d-%02d-%02d", $year + 2000, $month, $day);
查看更多
爷、活的狠高调
3楼-- · 2020-04-21 01:47

No need to do to DateTime for this. Time::Piece has been included with the Perl core distribution for years.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $date = '4/25/10';

my $date_tp = Time::Piece->strptime($date, '%m/%d/%y');

say $date_tp->strftime('%Y-%m-%d');
查看更多
Lonely孤独者°
4楼-- · 2020-04-21 02:05
use DateTime::Format::Strptime;
my $strp = DateTime::Format::Strptime->new(
    pattern   => '%m/%d/%y',
    locale    => 'en_US'
);
my $dt = $strp->parse_datetime('4/25/10');
print $dt->strftime('%Y-%d-%m'), "\n";

Gives:

2010-25-04
查看更多
Deceive 欺骗
5楼-- · 2020-04-21 02:10

You're not that far off.

Instead of splitting and joining in a single operation, you can keep individual variables to handle the data better:

my ($d,$m,$y) = split /\//, $str;

Then you can format it in most any way you please, for example:

printf "20%02d-%02d-%02d\n", $y, $d, $m;

A few notes, though:

  • I won't comment about the source format, but the format you're converting to doesn't make a lot of sense. You'd probably be better using ISO-8601: 2010-04-25.
  • Obviously, this way of doing only works up to year 2099.
  • For anything more serious, you'd be better off delegating this kind of work to date handling modules. See for example this question for parsing and this question for formatting
查看更多
登录 后发表回答