Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date::Calc - format the day and month

Tags:

date

perl

All I am trying to do here is if the day or month is a single digit, to add a zero in the front of it. Right now it prints out the date as 201188, and I am looking for 20110808.

#!/usr/bin/perl
use Date::Calc qw(Add_Delta_Days); 
my (undef, undef, undef, $day, $month, $year) = localtime(); 
$year +=1900; 
$month +=1; 
($year, $month, $day ) = Add_Delta_Days($year, $month, $day, -3)
if ($month =~ /\d{1}/){
    s/$month/0$month/
}  
if ($day =~/\d{1}/){ 
    s/$day/0$day/
}
print $year,$month,$day; 
like image 226
capser Avatar asked Aug 12 '11 01:08

capser


People also ask

How do you format month and day?

The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).

How do I format month and day in Excel?

Select the cells you want to format. Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.

How do I change the date format in Excel to DD MMM YYYY using formula?

First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay. It will format the dates you specify.

How do I change the date format in Openoffice Calc?

Right click on the date field you want formatted and select the Control... menu. From that, select the General tab, then scroll down to Date Format and select the elipses '..." button. Here you can modify the formatting of the date for the Form.


2 Answers

If you're happy to use Date::Calc, why not use DateTime ?

use DateTime;
my $date = DateTime->now;
$date->subtract(days => 3);
print $date->ymd;

In fact you can reduce that to:

print DateTime->now->subtract(days => 3)->ymd
like image 55
RET Avatar answered Oct 05 '22 09:10

RET


Use printf instead:

printf "%d-%02d-%02d", $year, $month, $day;

Gives output such as:

C:\perl>perl -we "printf qq(%d-%02d-%02d), 2011,5,4"
2011-05-04
C:\perl>perl -we "printf qq(%d-%02d-%02d), 2011,5,12"
2011-05-12
C:\perl>perl -we "printf qq(%d-%02d-%02d), 2011,22,12"
2011-22-12
like image 28
TLP Avatar answered Oct 05 '22 11:10

TLP