Separate zero from dates

Asked

Viewed 253 times

1

Guys I’m having a hard time, like I do to take out the zero when I pull the date for a variable ?

Example:

$mesAtual = date("m");
var_dump($mesAtual);

resultado: 06 

ESPERADO: 6
  • converts to whole

  • 1

    Use int to force the value to integer: $mesAtual = (int) date("m")

3 answers

4

Just use the n instead of m, according to the documentation:

Numerical representation of a month, zero left

Therefore:

$mesAtual = date('n');
var_dump($mesAtual);

// = string(1) "6"

Test this.

It will be sufficient, so the representation will be from 1 to 12, instead of 01 to 12.

  • I knew there was such an option, I looked in the documentation and did not see :(

3


Convert the return to the whole type:

$mesAtual = (int) date("m");

In this way, var_dump will result in:

int(6)

If you prefer, you can use the function intval

$mesAtual = intval(date("m"));

This function has a second parameter that defines the numerical basis of the result. By default it is 10 and therefore in this case it does not need to be specified. A basic test, using differences of microtimes, indicates that to do only the type cast is faster than calling the function (in Ideone it was shown much faster).

define("START", microtime(TRUE));

$mesAtual = intval(date("m"));

define("MIDDLE", microtime(TRUE));

$mesAtual = (int) date("m");

define("END", microtime(TRUE));

echo "intval: ", MIDDLE - START, PHP_EOL;
echo "type cast: ", END - MIDDLE, PHP_EOL;

Upshot:

intval: 0.043507099151611
type cast: 3.814697265625E-6

See working on Ideone.

  • Thank you very much.

  • @Carolinesilveira, if the answer solved the problem, can mark as solved.

0

Using Regular Expression example - ideone

$stt = strftime('%m', strtotime("06/04/2017")); 

echo preg_replace('/0(\d)/', '$1', $stt);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.