Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the date formats in Perl?

Tags:

perl

I just want to convert the dates from 20111230 format to 30-dec-2011.

like image 430
user1122213 Avatar asked Dec 30 '11 02:12

user1122213


People also ask

How do I format a date in Perl?

The Perl POSIX strftime() function is used to format date and time with the specifiers preceded with (%) sign. There are two types of specifiers, one is for local time and other is for gmt time zone.

How do I change the format of a date variable?

From the Variable Manager -> Show System Variable -> Data-Time -> In front of the date click on ... button -> Select the format.

How do I standardize a date format?

To quickly use the default date format, click the cell with the date, and then press CTRL+SHIFT+#.

How do I get the difference between two dates in Perl?

$bree = 361535725; # 16 Jun 1981, 4:35:25 $nat = 96201950; # 18 Jan 1973, 3:45:50 $difference = $bree - $nat; print "There were $difference seconds between Nat and Bree\n"; There were 265333775 seconds between Nat and Bree $seconds = $difference % 60; $difference = ($difference - $seconds) / 60; $minutes = $difference ...


2 Answers

In keeping with TMTOWTDI, you can use Time::Piece

#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t = Time::Piece->strptime("20111230", "%Y%m%d");
print $t->strftime("%d-%b-%Y\n");
like image 62
JRFerguson Avatar answered Nov 15 '22 06:11

JRFerguson


If I can't use one of the date modules, POSIX isn't so bad and it comes with perl:

use v5.10;
use POSIX qw(strftime);

my $date = '19700101';

my @times;
@times[5,4,3] = $date =~ m/\A(\d{4})(\d{2})(\d{2})\z/;
$times[5] -= 1900;
$times[4] -= 1;

# strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)
say strftime( '%d-%b-%Y', @times );

Making @times is a bit ugly. You can't always get what you want, but if you try sometimes, you might find you get what you need.

like image 35
brian d foy Avatar answered Nov 15 '22 07:11

brian d foy