如何在Perl中格式化日期?

时间:2009-02-22 16:37:26

标签: perl date templates

我正在修改Xcode中预先存在的脚本以自定义我的文件头。脚本是Perl,它不是我最好的语言。 :)

我只需要以dd / mm / yy格式在标题中插入当前日期。

这是我的剧本:

#! /usr/bin/perl -w
# Insert HeaderDoc comment for a header
#
# Inserts a template HeaderDoc comment for the header.
use strict;

# get path to document
my $headerPath = <<'HEADERPATH';
%%%{PBXFilePath}%%%
HEADERPATH
chomp $headerPath;
my $rootFileName = &rootFileNameFromPath($headerPath);

print "/*";
print " * $rootFileName\n";
print " * Project\n";
print " *\n";
print " * Created by Me on ";
# in bash it would be something like that :
# date +%d/%m/%y | awk '{printf "%s\n", $1}';
print " * Copyright 2009 My_companie. All rights reserved.\n";
print " *\n";
print " */\n";

sub rootFileNameFromPath {
    my $path = shift;

    my @pathParts = split (m'/', $path);
    my $filename = pop (@pathParts);
    my $rootFileName = "$filename";
    $rootFileName =~ s/\.h$//;
    return $rootFileName;
}

exit 0;

我刚刚修改了print命令,所以不要问我剩下的代码:)

3 个答案:

答案 0 :(得分:19)

不是删除strict(!),为什么不让代码strict干净?

my ($mday, $mon, $year) = (localtime(time))[3, 4, 5];

$mon  += 1;
$year += 1900;

printf "%02d/%02d/%02d\n", $mday, $mon, $year % 100;

甚至可能更好(因为对于按Bash提问的人更熟悉):

# At the top, under use strict;
use POSIX qw/strftime/;

# then later...
my $date = strftime "%d/%m/%y", localtime;
print "$date\n";

有趣的巧合:Perl Training Australia发布半常规tips(您可以通过电子邮件或在线获取),就在今天strftimea new one

答案 1 :(得分:9)

您还可以使用DateTime和相关模块,这对于像这样的小脚本来说当然是完全矫枉过正的。但是对于更大的应用程序,你应该使用可靠的模块,而不是做很长的事情。为了记录,使用DateTime你会写:

DateTime->today()->strftime('%d/%m/%y');

或者您可以使用更现代的CLDR格式语言:

DateTime->today->format_cldr('dd/MM/YYYY');

答案 2 :(得分:2)

@time = localtime(time);
$mday = $time[3];
$mon = $time[4]+1;
$year = $time[5]+1900;
print "$mday/$mon/$year\n";

应该这样做。

编辑:

printf "%02d/%02d/%4d",$mday,$mon+1,$year+1900";

也会使用零来处理填充。