php date format

3

I have this date in php:

31082016

And I want to pass it to this format:

dd-mm-yyyy

I have the following code, but it gives me an error:

echo "<br/><hr/>" . $fechaIn . "<hr/><br/>";
echo "<br/><hr/>" . date('d-m-Y', $fechaIn) . "<hr/><br/>";

And it shows me the following:

<br/>
<hr/>31082016<hr/>
<br/>
<br/>
<hr/>26-12-1970<hr/>
<br/>

What could be the problem?

    
asked by Mariano 18.08.2016 в 11:00
source

3 answers

7

You have another option that would be to separate each element and treat it later.

Maintaining the pattern you have started;

$fechaIn = '31082016';

$y = substr( $fechaIn, 4, 4 );
$m = substr( $fechaIn, 2, 2 );
$d = substr( $fechaIn, 0, 2 );

echo "<br/><hr/>" . $fechaIn . "<hr/><br/>";
echo "<br/><hr/>" . date( 'd-m-Y', mktime( 0, 0, 0, $m, $d, $y ) ) . "<hr/><br/>";
    
answered by 18.08.2016 / 11:26
source
6

The date() function takes as a parameter a number that is a timestamp (that is, the number of seconds that passed since 01/01/1970), so it returns that date.

Modify the string directly

What you have is a string that is formed as ddmmaaaa (day-month-year). The only thing you need to give it the format you are looking for is to add the scripts to separate them.

We use substr_replace() to add a script to the position 2 and in position 4:

echo substr_replace(substr_replace($fechaIn, '-', 4, 0), '-', 2, 0);


Convert a string to date

If you would like to convert the string to date format first, the best option is to use DateTime :: createFromFormat () :

$fechaIn = '31082016';

//Convertir un string a fecha
$fechaDateTime = DateTime::createFromFormat('dmY', $fechaIn);

//Imprimir la fecha en el formato deseado
echo $fechaDateTime->format('d-m-Y');

Result

31-08-2016
    
answered by 18.08.2016 в 11:18
4

Three examples in the format you indicate:

Example 1

<?php
$source = '2012-07-31';
$date = new DateTime($source);
echo $date->format('d.m.Y'); // 31.07.2012
echo $date->format('d-m-Y'); // 31-07-2012
?>

Example 2

date("d/m/Y", strtotime($str));

Example 3

$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
  

I recommend you look at formats and more features Here and Here

    
answered by 18.08.2016 в 11:20