How to catch the first and last day of the current month ? PHP

Asked

Viewed 2,437 times

1

Hello, everybody.

I would like to take the first and last day of the current month and store them in two variables to use them in a query condition of a MYSQL query.

You know a way to accomplish this ?

Thank you in advance. Thank you!

1 answer

5


It has a form that will be presented here in a very generic way, but useful, which follows below:

<?php
// Definir a zona geográfica padrão.
date_default_timezone_set("America/Sao_Paulo");

// Pegar o último dia.
$P_Dia = date("Y-m-01");
$U_Dia = date("Y-m-t");

print "Teste de Data Inicial :: " . $P_Dia . "<br>";
print "Teste de Data Final :: " . $U_Dia . "<br>";

// Inicializar conexão PDO.
$DSN = "mysql:127.0.0.1/Database";
$Username = "root";
$Password = "123456";
// Inicilizar conexão.
$Connect = new PDO($DSN, $Username, $Password) or die(NULL);

// Preparar transação.
$Statement = $Connect->prepare("
    SELECT
       Campo1,
       Campo2,
       CampoN
    FROM MinhaTabela
    WHERE DataInicio = :DataI
      AND DataFim = :DataF");

$Statement->bindParam(":DaiaI", $P_Dia);
$Statement->bindParam(":DataF", $U_Dia);
$Statement->execute();

// Segue o fluxo de tratamento...
?>

Whatever thing says I set something missing.

  • Speak there, @Luis Alberto. From what I can see, you are using PDO. I use mysqli. But I will try to see if I adjust your code according to mine.

  • I noticed that on the date you used the "t". What good would this "t" ?

  • To take the last day of the month.

  • All right, Luis. It worked out here. Thank you!

Browser other questions tagged

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