3

i have wriiten the following code to fetch date from server and to display it in yy/mm/dd-hh/mm/ss format.

#!/usr/bin/perl
system(`date '+ %Y/%m/%d-%H:%M:%S' >ex.txt`);
open(MYINPUTFILE, "/tmp/ranjan/ex.txt");
while(<MYINPUTFILE>)
{
    chomp;
    print "$_\n";
}
close(MYINPUTFILE);

output:

2013/07/29-18:58:04

I want to add two minutes to the time and need to replace the time present in a file, Pls give me some ideas.

4

2 回答 2

4

更改日期命令以添加 2 分钟:

date --date "+2 min" '+ %Y/%m/%d-%H:%M:%S'

或 Perl 版本:

use POSIX;
print strftime("%Y/%m/%d-%H:%M:%S", localtime(time + 120));
于 2013-07-29T13:53:08.487 回答
3

最好用来Time::Piece做日期的解析和格式化。它是一个内置模块,不需要安装。

不同寻常的是,在这种情况下,替换日期/时间字符串的长度与从文件中读取的原始字符串的长度完全相同,因此可以就地进行修改。通常文件的总长度会发生变化,因此需要创建一个新文件并删除旧文件,或者将整个文件读入内存并再次写出。

该程序打开文件以同时读/写,从文件中读取第一行,使用 解析它Time::Piece,添加两分钟(120 秒),再次寻找文件的开头,并打印重新格式化的新日期/时间与原始文件相同的方式。

use strict;
use warnings;
use autodie;

use Time::Piece;
my $format = '%Y/%m/%d-%H:%M:%S';

open my $fh, '+<', 'ex.txt';

my $date_time = <$fh>;
chomp $date_time;
$date_time = Time::Piece->strptime($date_time, $format);

$date_time += 60 * 2;

seek $fh, 0, 0;
print $fh $date_time->strftime($format);
close $fh;

输出

2013/07/29-19:00:04
于 2013-07-29T15:30:26.973 回答