Add a 0 to the start of a number

Hi All

I am working on some code and have been saving months as 2 digits… e.g. Jan is 01, Feb 02 and so on.

I have written code that will take a month stored in the DB and add whatever number of months needed.

FOR EXAMPLE - This is due in month 07 and then due again in 1 month.

My code basically checks if the current month matches and the stored month and if it does it updates the stored month by the number in the DB.

As per above it takes 07 and adds 1.

The issues is that I need 08 but it is changing it and storing it as 8.

Do you know how I can force it back to 08?

Thanks for any help.

mrmbarnes

I would have thought that it was better to store the month number without the leading zero. A leading zero makes the month a string.

Retrieving and incrementing the month is simpler and using sprintf (…); to display with a leading zero when required.

2 Likes

Thanks for the help… from that I have worked it out… if anyone wants my test code it is:

$month = “8”;

$newMonth = sprintf("%02s",$month);

print $newMonth;

1 Like

https://www.php.net/manual/de/function.str-pad.php

I suppose you could use MySQL’s LPAD

I don’t know the situation so I am likely off base, but I have a feeling more thought is being given to “appearance” rather what’s most appropriate for how the value will be used.

I would be inclined to have the value in a date / time field instead of string or numeric assuming most of the functions to be used working with the value would be date / time functions not string functions. I would prefer to use string functions to display the value not to work with it.