0

I am facing an issue in echo date() with some formats like:

if i use the format d/m/Y like: '18/04/2017' then date() does not recognize this because the format contain /

<?php
  echo date("d-m-Y",strtotime('16/04/2017'));
?>

it will output: 01-01-1970

But when i use the format m/d/Y like: '04/18/2017' then date() it recognized

<?php
  echo date("d-m-Y",strtotime('04/16/2017'));
?>

it will output: 16-04-2017

I am not getting these different behaviour of date(), can anybody help me please

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
lazyCoder
  • 2,544
  • 3
  • 22
  • 41

3 Answers3

2

Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

So if your date is like 04/16/2017, change the / to - and then use date() function on it to convert it to any format.

Reference

Working Code

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
1

You can use date_create_from_format to convert your date to any format you want. The problem with your code was that strtotime does not support this format.

Learn about strtotime formats

If you using dd/mm/yyyy then it will not work because does not comes under support format of strtotime. For using

Supported formats: (for dd mm yyyy)

dd [.\t-] mm [.-] YY

Example: 16-04-2017

Example: 16.04.2017

Example: 16\t04t\2017

<?php
ini_set('display_errors', 1);
$date=date_create_from_format("d/m/Y","16/04/2017");
echo $date->format("d-m-Y");
Community
  • 1
  • 1
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

Another way is replace / with - of given date

$date = '16/04/2017';
$date = str_replace("/", "-", $date);
echo date("d-m-Y",strtotime($date));
Hardeep Singh
  • 743
  • 1
  • 8
  • 18