Mike Dray
Mike Dray

Reputation: 155

PHP Capturing Date in wrong format

I know there is probably a simple answer to this but I have tried several things and nothing seems to work.

I have the following data taken from a JSON array:

{
"Id": 21973679,
"InvoiceNumber": 13,
"IssueDate": "14/08/2017",
"EulerID": 6162023,
"CustomerName": "Alderley plc",
"TotalAmount": "1,704.00",
"TotalTaxAmount": 0,
"Currency": "USD",
"DueDate": "13/09/2017",
"AmountDue": "0",
"Status": "Paid"
},
{
"Id": 21974783,
"InvoiceNumber": 23,
"IssueDate": "09/01/2017",
"EulerID": 6162023,
"CustomerName": "Alderley plc",
"TotalAmount": "11,000.00",
"TotalTaxAmount": 0,
"Currency": "GBP",
"DueDate": "08/02/2017",
"AmountDue": "0",
"Status": "Paid"
}, 

I am trying to get the IssueDate and DueDate. Both are stored in the format dd/mm/yyyy. However whatever I do php seems to not be able to capture them consistently.

$report_starting_date=$item1['IssueDate'];

$report_starting_date=date('d/m/Y',strtotime($report_starting_date));

For the 2nd Item invoice (23) it works fine if I echo the month it will return 1 this seems to work as the date could be either dd/mm or mm/dd however in the 1st item invoice (13) 14 cannot be a month and so php seems to set the date as 01/01/1970. I have no idea why I can store one item correct and not the other?

Thanks

Upvotes: 0

Views: 717

Answers (4)

sathish R
sathish R

Reputation: 422

You could use the below code to convert date string to date. You need to supply the format of the date as first argument and date string as second argument.

$date = DateTime::createFromFormat('d/m/Y', $item1['IssueDate'])->format('d/m/Y');

Function format() returns date as string in supplied format.

Upvotes: 0

Artem Ilchenko
Artem Ilchenko

Reputation: 1035

Try this:

$date = DateTime::createFromFormat('d/m/Y', $item1['IssueDate']);

Same:

$date = date_create_from_format('d/m/Y', $item1['IssueDate']);

CreateFromFormat doc

In $date you have instance of DateTime class so you can print value using format() method like this $date->format('d/m/Y');

Format method doc

Upvotes: 2

Skoempie
Skoempie

Reputation: 1181

The format 'dd/mm/yyyy' isn't supported with strtotime. Replacing the slashes with a dashes does fix your problem.

$time = strtotime(str_replace('/', '-', $item1['IssueDate']);
$report_starting_date = date('d/m/Y', $time);

Note that this is more like a workaround which is not quite failsave. @kchason's answer might be the better choice here.

Upvotes: 0

kchason
kchason

Reputation: 2885

Per the PHP documentation on supported formats, dd/mm/YYYY is not supported for strtotime.

You could use the createFromFormat function, and the documentation is here.

<?php
$date = date_create_from_format('d/m/Y', $item1['IssueDate']);
echo date_format($date, 'Y-m-d');
?>

Upvotes: 5

Related Questions