fomatar data php

1

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

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 dateformat as yy-mm-dd in the datapicker, but that 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 , it returns me as if the date was empty ( 1970-01-01 )

    
asked by anonymous 28.05.2017 / 19:02

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' in single quotation marks is not processed, change to double quotation marks "$ini"

In PHP, double-quotes (") and single quotes (') as well as other languages also define a string, but there are differences between them. Strings consisting of double quotation marks are dynamic, the value of a variable within the context, if it has a variable of course, whereas the single quotes are static and do not provide mechanisms for the variation of its contents even if it has a variable defined in it.

  • $ test = 10;

    echo 'Pele's shirt number was $ test';

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

  • $ test = 10;

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

    output: O numero da camisa do Pelé era 10

We can clearly see the difference between the two forms. So if there is doubt as to when to use one form or use the other form keep in mind that double quotation marks 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 the double quotation marks, otherwise use single quotation marks.

    
28.05.2017 / 22:12