fomatar data php

Asked

Viewed 47 times

0

I’m trying to convert a date that comes from a datapicker, the date comes in format dd/mm/yy, but in order to work with it in mysql, I need it to be in the format yyyy-mm-dd.

I’m using the following code:

    $ini = $_POST['inicio'];
    $newDateini = date( "Y-m-d", strtotime('$ini'));
    $newDatefim = date("Y-m-d", strtotime($_POST['fim']));

PS: I could put the dateformat as yy-mm-dd in the datapicker, but this would make the date confusing for the user.

If I select today’s date, for example, and request a echo $ini the result will be 28/05/2017. But when I request a echo $newDateini instead of returning the date in 2017-05-28, returns to me as if the date is empty(1970-01-01)

  • right... and what’s the problem?

  • @Frenetic, I didn’t notice that I hadn’t asked the question halfway, sorry. I edited the question spelled out the problem

  • https://answall.com/a/21841/250 ;)

1 answer

0


example - ideone

$ini = "28/05/2017";
$ini =str_replace("/", "-", $ini);
$newDateini = date( "Y-m-d", strtotime("$ini"));

echo $newDateini;

strtotime - Interprets any date/time description in English text in Unix timestamp

The variable '$ini' between single quotes is not processed, change to double quotes "$ini"

In PHP double quotes (") and single quotes (') as well as other languages also define a string, but there are differences between them. Strings formed by double quotes are dynamic, that is, their content is changed according to the value of a variable within the context, if you have a variable of course. While single quotes are static and do not provide mechanisms for varying their content even if it has a variable defined on it. Examples.

  • $test = 10;

    echo 'Pelé’s shirt number was $test';

    exit: O numero da camisa do Pelé era $teste

  • $test = 10;

    echo "Pele’s shirt number was $test";

    exit: O numero da camisa do Pelé era 10

We can clearly see the difference between the two forms. So if there is any doubt when to use one form or use the other form keep in mind that double quotes are dynamic and interpretive while single quotes are static. So if you want to include in your string a variable value or one of the characters ( n, r, t, r n) use double quotes, otherwise use single quotes.

  • Thanks for the explanation Leo, it helped a lot!

Browser other questions tagged

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