r/PHPhelp • • 2d ago

Solved strftime Help

Hi,

I've just upgraded my shop and PHP to 8.1.

I'm seeing errors which I need help with please.

I've googled strftime and can see that it is deprecated, but can't figure out how to correct the code. Can someone please help? Code portions below:

for ($i = 1; $i <= 12; $i++) {                                                                             $data['months'][] = array(
'text'  => strftime('%B', mktime(0, 0, 0, $i, 1, 2000)),
'value' => sprintf('%02d', $i)
); 
}

$today = getdate();

$data['year_valid'] = array();

for ($i = $today['year'] - 10; $i < $today['year'] + 1; $i++) {
$data['year_valid'][] = array(
'text'  => strftime('%Y', mktime(0, 0, 0, 1, 1, $i)),
'value' => strftime('%Y', mktime(0, 0, 0, 1, 1, $i))
);
}                                 }                                   

$data['year_expire'] = array();

for ($i = $today['year']; $i < $today['year'] + 11; $i++) {
$data['year_expire'][] = array(
'text'  => strftime('%Y', mktime(0, 0, 0, 1, 1, $i)),
'value' => strftime('%Y', mktime(0, 0, 0, 1, 1, $i))
);
}
6 Upvotes

12 comments sorted by

3

u/Takeoded 2d ago

To replace it you first need to know what locale your server use.

What does var_dump(setlocale(LC_TIME, 0)); return on your server?

For example, if var_dump(setlocale(LC_TIME, 0)); returns de_DE then you you replace it with:

$fmt = new IntlDateFormatter(
    'de_DE',
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    null,
    null,
    'LLLL' // standalone month name
);

$data['months'] = array();
for ($i = 1; $i <= 12; $i++) {
    $data['months'][] = array(
        'text'  => $fmt->format(mktime(0, 0, 0, $i, 1, 2000)),
        'value' => sprintf('%02d', $i)
    );
}

1

u/TemplerTreiff 14h ago

only problem with IntlDateFormatter on older shop installs is that the intl extension isnt always enabled by default when you bump to 8.1

3

u/HolyGonzo 2d ago edited 2d ago

Assuming you are simply populating $data (my guess is that this is being used to help set up dropdown options) and don't need the $today variable for anything else, you don't need any special formatting nor any extra libraries - you only need date("Y") to get the current year.

And unless you're setting up code to be used in different servers with different locales, you can just hardcode the months and it will be easier to read in the future and not use any functions.

This little snippet (just fix the month names if needed) will give you the exact same $data variable and be much easier to read:

$data = [
  "months" => [
    [ "text" => "January",   "value" => "01" ],
    [ "text" => "February",  "value" => "02" ],
    [ "text" => "March",     "value" => "03" ],
    [ "text" => "April",     "value" => "04" ],
    [ "text" => "May",       "value" => "05" ],
    [ "text" => "June",      "value" => "06" ],
    [ "text" => "July",      "value" => "07" ],
    [ "text" => "August",    "value" => "08" ],
    [ "text" => "September", "value" => "09" ],
    [ "text" => "October",   "value" => "10" ],
    [ "text" => "November",  "value" => "11" ],
    [ "text" => "December",  "value" => "12" ]
  ],
  "year_valid" => [],
  "year_expire" => []
];

// Loop from 10 years ago to 10 years in the future. Past years go into year_valid, while future years go into year_expire. The current year goes into both. 

$this_year = date("Y");

for($yyyy = $this_year-10; $yyyy <= $this_year+10; $yyyy++)
{
  if($yyyy <= $this_year)
    $data["year_valid"][] = ["text" => $yyyy, "value" => $yyyy];
  if($yyyy >= $this_year)
    $data["year_expire"][] = ["text" => $yyyy, "value" => $yyyy];
}

If you truly need the best date/time library, you can load Carbon but that's very likely overkill.

In the majority of the cases, you can either use date() or the DateTime class to do most of the work. I used date() here for simplicity but if date() ever became deprecated you could replace:

$this_year = date("Y");

with:

$this_year = (new \DateTime())->format("Y");

The DateTime class has some very nifty features. For example, you can use descriptive, relative dates like:

echo (new \DateTime("3 weeks ago"))->format("Y-m-d H:i:s");

echo (new \DateTime("-30 hours"))->format("Y-m-d H:i:s");

echo (new \DateTime("+30 hours"))->format("Y-m-d H:i:s");

1

u/Johto2001 2d ago edited 2d ago

The first part is an array of months. date takes a timestamp exactly the same as strftime, and the date function takes 'F' which is equivalent to strftime's 'B'. That should get you started, the other two arrays are prepared similarly and can be ported similarly.

All the information you need is available in the PHP documentation https://www.php.net/manual/en/function.strftime.php

One caveat: this does not handle localized month names, so if you need that look at /u/Takeoded 's comment which uses the php-intl extension. I avoided that because it's not always available, but if it is then use it. 

By the way, you have a latent Y2038 bug in that code that could activate in 2029 if the code runs on a 32-bit system. It's the mktime calls on the lines starting text and value. Just occured to me.

1

u/martinbean 2d ago

I pasted your code into a text editor to try and fix the formatting, but the opening and closing curly brackets aren’t balanced.

Can you instead explain the intention of the code? Since it looks like you’ve copied-and-pasted multiple snippets and it’s difficult to distinguish where one ended and another starts.

1

u/optimusprimepluto 2d ago edited 2d ago

Simply

$formatter = new IntlDateFormatter(
    setlocale(LC_TIME, '0') ?: Locale::getDefault(),
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    date_default_timezone_get(),
    IntlDateFormatter::GREGORIAN,
    'MMMM'
);

$data['months'] = [];

for ($i = 1; $i <= 12; $i++) {
    $data['months'][] = [
        'text'  => $formatter->format(mktime(0, 0, 0, $i, 1, 2000)),
        'value' => sprintf('%02d', $i)
    ];
}

$today = getdate();

$data['year_valid'] = [];

for ($i = $today['year'] - 10; $i < $today['year'] + 1; $i++) {
    $year = date('Y', mktime(0, 0, 0, 1, 1, $i));
    $data['year_valid'][] = [
        'text'  => $year,
        'value' => $year
    ];
}

$data['year_expire'] = [];

for ($i = $today['year']; $i < $today['year'] + 11; $i++) {
    $year = date('Y', mktime(0, 0, 0, 1, 1, $i));
    $data['year_expire'][] = [
        'text'  => $year,
        'value' => $year
    ];
}

1

u/brianozm 1d ago edited 1d ago

The old form strtotime() function does literally nearly all of this work for you. This is a marvellous function and there are equivalent object functions mentioned above. Don’t waste time writing this code yourself, you’ll never get it right.

Caveat: there are some date separator ambiguity problems with strtotime() “-“ and “/“ - see doco for info.

https://www.php.net/manual/en/function.strtotime.php

1

u/alesseon 2d ago

Look at the DateTime object, specifically the format method and setDate or modify methods

1

u/dabenu 2d ago edited 2d ago

For now that's just a deprecation. It shouldn't break anything. It's planned to be removed in php9, but that's not released yet.

There's plenty of tools that can automatically migrate this for you, like rector, or you can just use any AI. You can also look up the alternatives mentioned in the official documentation and rewrite it yourself. 

Also you know php8.1 has been EOL for 2 years 1 year already, right? You might want to upgrade to php8.6 instead.

3

u/mattdahack 2d ago

*laughs over here* Still running version PHP 5.6.40 from 2019 ish era.

1

u/Alexander-Wright 2d ago

If you are using composer, have a look at the nesbot/carbon package.

It wraps up all the date/time functions in a neat object.

0

u/Basic_Reporter9579 2d ago

try Carbon\Carbon.