2

How to display the day of the year in 3 digits format so that January 1st is not "1", but "001"?

I'm curious as to whether such a function is implemented (something like date('zzz') ) or not, so I have to work on date('z') and check if it's less than 100, 10?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

4 Answers4

4

strtotime usage is discouraged. This should work:

echo sprintf('%03d', date('z'));
ddinchev
  • 33,683
  • 28
  • 88
  • 133
3
function pad_date($date)
{
    return str_pad(date('z', $date), 3, '0', STR_PAD_LEFT);
}

It is better to accept UNIX time in the function as above and use the str_pad function

Tak
  • 11,428
  • 5
  • 29
  • 48
1

If there isn't such a function, my approach to such numerical padding needs is usually to do this:

$three_digit_day_num_string = substr('000' . date('z', $timestamp), -3);
Tom Haws
  • 1,322
  • 1
  • 11
  • 23
-1
function pad_date($date) {
    $mydate = date('z', $date);
    return str_repeat("0", 3-strlen($mydate) ).$mydate;
}

echo pad_date(time())."\n"; // today
echo pad_date(time() - (100 * 24 * 60 * 60))."\n"; // 100 days ago
echo pad_date(time() - (200 * 24 * 60 * 60))."\n"; // 200 days ago
echo pad_date(time() - (300 * 24 * 60 * 60))."\n"; // 300 days ago
echo pad_date(time() - (335 * 24 * 60 * 60))."\n"; // 335 days ago
abcde123483
  • 3,885
  • 4
  • 41
  • 41
  • I think that this is probably either answering a different question or maybe is just too long an answer. I'm not sure. – Tom Haws Dec 04 '11 at 22:03