【问题标题】:Convert specific number date to show month将特定数字日期转换为显示月份
【发布时间】:2013-07-02 10:58:03
【问题描述】:

想要转换例如那个日期:

02082012

In that case:
02 - Day
08 - Month
2012 - Year

现在我将日期分开但无法转换为月份:

#echo "02082012"|gawk -F "" '{print $1$2 "-" $3$4 "-" $5$6$7$8}'
#02-08-2012

转换后的预期视图并捕获所有月份:

02-Aug-2012

【问题讨论】:

  • 你可以这样做:date -d'08/02/2012' "+%d-%b-%Y" 给出02-Aug-2012
  • 在这种情况下,我会以该格式获得输入 02082012
  • 是的,我明白了,我遇到的问题是“02082012”不是date 可接受的格式。
  • 为什么要使用 perl 标签?该问题与 Perl 无关。
  • 也许你是对的,但在大多数情况下,我使用 perl 是因为尝试学习语言......如果冒犯了你,请见谅。

标签: perl scripting sed awk tr


【解决方案1】:

直截了当:

kent$ date -d "$(echo '02082012'|sed -r 's/(..)(..)(....)/\3-\2-\1/')" "+%d-%b-%Y"
02-Aug-2012

【讨论】:

    【解决方案2】:

    另一个使用 POSIX 模块的 Perl 解决方案,它位于 Perl 核心中。

    use POSIX 'strftime';
    
    my $date = '02082012';
    print strftime( '%d-%b-%Y', 0, 0, 0,
      substr( $date, 0, 2 ),
      substr( $date, 2, 2 ) - 1,
      substr( $date, 4, 4 ) - 1900 );
    

    查看http://strftime.net/ 可以很好地了解strftime 的占位符的作用。

    【讨论】:

      【解决方案3】:

      使用 Perl 的 POSIX 模块和strftime 看起来像

      #! /usr/bin/env perl
      
      use strict;
      use warnings;
      
      use POSIX qw/ strftime /;
      
      while (<>) {
        chomp;
      
        if (my($d,$m,$y) = /^(\d\d)(\d\d)(\d\d\d\d)$/) {
          print strftime("%d-%b-%Y", 0, 0, 0, $d, $m-1, $y-1900), "\n";
        }
      }
      

      输出:

      $ echo 02082012 |转换日期
      2012 年 8 月 2 日

      【讨论】:

        【解决方案4】:

        Time::Piece 是一个核心 Perl 模块,非常适合像这样的简单操作。

        #!/usr/bin/perl
        
        use strict;
        use warnings;
        use 5.010;
        use Time::Piece;
        
        my $string = '02082012';
        
        my $date = Time::Piece->strptime($string, '%d%m%Y');
        
        say $date->strftime('%d-%b-%Y');
        

        (是的,这与 user1811486 的答案非常相似 - 但它使用原始问题中要求的正确格式。)

        【讨论】:

          【解决方案5】:

          我是这样想的.....

          use 5.10;
          use strict;
          use warnings;
          use Time::Piece;
          my $date = '2013-04-07';
          my $t = Time::Piece->strptime($date, '%Y-%m-%d');
          print $t->month;
          print $t->strftime('%Y-%b-%d');
          

          我刚刚试过这个......

          【讨论】:

            【解决方案6】:

            要拆分具有固定字段长度的字符串,请使用unpack

            my $input = "02082012";
            my ( $day, $month, $year ) = unpack( 'a2 a2 a4', $input );
            print "$input becomes $day, $month, $year\n";
            

            http://perldoc.perl.org/functions/unpack.html

            然后,如其他答案所述,使用 POSIX::strftime() 重新格式化日期。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-11-26
              • 1970-01-01
              • 2017-06-02
              • 1970-01-01
              • 2018-12-24
              相关资源
              最近更新 更多