PHP Date strtotime - php

I'm facing a problem with date formating and adding days.
I have a function like this:
public function test($date)
{
var_dump($date);
var_dump(date("d/m/Y", strtotime($date . '+ 1 days' )))
}
for this example if I use "02/09/2019" as date I get:
02/09/2019
10/02/2019
I'm expecting
02/09/2019
03/09/2019
Can someone help me find a solution to this problem?
Thanks

The essential problem here is that PHP is interepreting $date as a different one to the date you intended it to represent. This is because you're using an ambiguous format for the date. Depending on your cultural norms, 02/09/2019 could mean 2nd September (d/m/Y format - commonly used in Europe and other places) or 9th February (m/d/Y format - commonly used in North America and other places).
PHP is treating your string as if it's an m/d/Y format, and adding one day to it - hence you get 10th February as the result.
However, this shouldn't be too much of a surprise. What it will do with your string is documented and predictable. The strtotime manual says, in the notes:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed. If, however, the year is given in a two digit format and
the separator is a dash (-), the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
dates or DateTime::createFromFormat() when possible.
There are two basic ways to solve this, which I've demonstrated in the "test" and "test2" functions in the code sample below.
The first approach, in the "test" function keeps your existing code the same, but inputs the date in the universal Y-m-d format, so there's no confusion over which part is the day and which the month.
If that's not workable for you for some reason, then the second approach changes the code to use the DateTime::createFromFormat function, which will parse the date according to the format string you pass to it, and create a DateTime object which can then be manipulated and also re-formatted again (into any string format you choose) when you're ready to output it.
<?php
function test($date)
{
var_dump($date);
var_dump(date("d/m/Y", strtotime($date . '+ 1 days' )));
}
function test2($date)
{
var_dump($date);
$dt2 = DateTime::createFromFormat("d/m/Y", $date);
$dt2->add(new DateInterval('P1D'));
var_dump($dt2->format("d/m/Y"));
}
test("2019-09-02");
test2("02/09/2019");
output of "test":
"2019-09-02"
"03/09/2019"
output of "test2":
"02/09/2019"
"03/09/2019"
Demo: http://sandbox.onlinephpfunctions.com/code/71e07798a109859cabd242d77acb1eafaef5bfe8

Have you tried using Carbon a php date-time library. it makes working with dates very easy, it is very easy to format dates and add dates using this library. Here is a quick tutorial
$dt = Carbon::create(2019, 09, 02, 0);
echo $dt->addDays(1);

Basically the 09 is been considered as day so its adding +1 to it so output is 10/02/2019.The provided solution may not be perfect but it should serve your purpose.
echo date("d/m/Y", strtotime(str_replace('/','-','02/09/2019') . '+1 days'));
which will give 03/09/2019

Related

Converting date in specific format to unix then comparing

I'm having problems comparing two dates in PHP. I want to compare the current date to one entered by a user.
$date = "18/05/2018";
The date input by the user.
$date_unix = strtotime($date);
Used to convert the date from the given format to time, in order to be compared.
if($date_unix < time()){
echo '<b>Notice:</b> You cannot specify a date in the past.<br>';
}
The above if statement is always run and i'm confused as to why. Any help would be appreciated.
strtotime makes assumptions about the date format, and in this case those assumptions are wrong.
You are using a day/month/year format (like me: that's the default format in Italy). Yesterday, a date of 12/05/2018 would have been taken by strtotime, and assumed to be december 5th, 2018. The test would have been passed, and apparently been correct.
And if it had been a reservation, it would have incurred in seven months' worth of charges ;-D
So always specify the format. For that, I feel that the best is using DateTime:
$date = date_create_from_format('d/m/Y', '18/05/2018');
for the same reasons, be wary how you calculate date differences.
(Also, be wary of Daylight Saving Time).
From the strtotime documentation:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed
As 18/05/2018 is not a valid date in the American format (where the first number represents the month), your strtotime call will return false. And false (zero) will always be less than time().
The simplest fix, if you are confident about the format of the input, would be to replace the slashes with dashes before converting to timestamp. strtotime will then interpret the string as an international date which will work correctly:
$date = str_replace('/', '-', "18/05/2018");
$date_unix = strtotime($date);
However, updating your code to use the DateTime class, as in smith or LSerni's answers, will probably give you more flexibility going forward.
should stop uing the legacy strtotime and start using the DateTime class
$date = "18/05/2018";
$newDate = DateTime::createFromFormat('d/m/Y', $date);
if (new DateTime() < $newDate) {
echo 'future';
}else{
echo 'past';
}
To fix this problem, using information provided above I used the explode() to split up the $date variable into an array then rearrange the resulting array. I then pieced the exploded variables back together to form the correct American date format.
Below is the code relating to the above description:
$splitdate = (explode("/",$date));
$splitdate_day = $splitdate[0];
$splitdate_month = $splitdate[1];
$splitdate_year = $splitdate[2];
$date_change = $splitdate_month . "/" . $splitdate_day . "/" . $splitdate_year;
if(strtotime($date_change) < time()){
echo '<b>Notice:</b> You cannot specify a date in the past.<br>';
}
This may not be the most efficent method, but it solved the issue I was encoutering.

How to check format of Date in PHP?

My SQL server uses the mm/dd/yyyy date format, but the date picker that I have implemented using jQuery gives the date format as dd/mm/yyyy.
So I coded this to check if the given input is in the format of mm/dd/yyyy, but it evaluates to true no matter which format the date input is given in. PHP code is,
$Temp = DateTime::createFromFormat('d/m/Y', $StartsOn);
if($Temp)
$Temp->format('m/d/Y');
I need to convert to mm/dd/yyyy format only if the input is in dd/mm/yyyy. So please tell me what is the logical error that I have made in my code.
it's impossible to reliably check if a date is in dd/mm/yyyy or mm/dd/yyyy format. just think about a date like "May, 7th".
this would be 07/05/2015 or 05/07/2015 depending on the format. so if you just got the date-string with no additional information you can't tell if for example 05/07/2015 is May, 7th or July, 5th.
I am sorry but there is no logical solution to your problem.
From the PHP manual on strtotime
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed. To avoid potential ambiguity, it's best to use ISO 8601
(YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
The reason passing the date to SQL server works as mm/dd/yyyy is because of the separator. Where possible it is always best to pass as YYYY-MM-DD as per ISO 8601 which was created for exactly this purpose. To fix your problem the best bet is to change the jQuery plugin configuration to output data in that format (if that's not possible, string replace / with - where it's coming from the jQuery plugin. This will avoid future complications by writing code to fix the date format.
You will no be able to tell the difference between mm/dd/yyyy and dd/mm/yyyy when you don't know where it's come from.
You can use a modified version of this function from PHP.net. It uses the DateTime class:
function validateDate($date)
{
$d = DateTime::createFromFormat('d/m/Y', $date);
return $d && $d->format('d/m/Y') == $date;
}
if(validateDate($StartsOn)){
//do job
}
function was copied from this answer or php.net

php sort time always give current data without formating given date

I have date 14.10.13 format it comes from my database table.I want to format it .but it give always today dates.I want to change it as following.
04 December 2014
for this i use flowing code
<?php echo date("d F Y", strtotime('14.10.13'));?>
but it always give current date
04 December 2014
format
i cannot understand what is problem.
If you have a known format then you can avoid the strtotime-magic by using ::createFromFormat
$input = '14.10.13';
$output = DateTime::createFromFormat('y.m.d', $input)->format('d F Y');
var_dump($output);
It's very simple
First you must store date in mysql in a 'date' datatype.
It stores in YYYY-MM-DD.
using DATE_FORMAT(column_name,'%d.%m.%Y') mysql query to fetch your date which is already inserted.
That's all. don't complicate it.
An excerpt from the official PHP documentation of strtotime():
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
dates or DateTime::createFromFormat() when possible.
I'll go for DateTime::createFromFormat().
Pass standard format in date()
<?php echo date("d F Y", strtotime('14-10-13'));?>
using . is not date standard so use - separated date
or by replaceing
<?php echo date("d F Y", strtotime(str_replace('.', '-','14.10.13')));?>

parse a date string

I have this string in a post variable
'03/21/2011'
I need to parse it via php and turn it into this format
'2011-03-21'
I am using php and i need this format so i can run this query
SELECT prospect as 'Prospect', company as 'Company', industry as 'Industry', created_at as 'Original Date Submitted', software as 'Software', warm_transfer as 'Warm Transfer', UserName as 'Sales Rep' FROM mercury_leads join user on UserID=user_id WHERE created_at BETWEEN '2011-01-01' AND '2011-03-22'
If you want to handle it in PHP, your best bet is to use the strtotime() function which converts a string into a time that can then be manipulated with the date() function.
So you'd do something like:
$dateStr = date('Y-m-d', strtotime('03/21/2011'));
The nice thing about using strtotime() is that you don't have to worry about the exact format of the string you pass in. As long as it's something semi-reasonable, it'll will convert it.
So it would handle 03/21/2011, 3-21-2011, 03-21-11 without any modifications or special cases.
You can parse it even from mysql
select str_to_date('03/21/2011','%m/%d/%Y')
$date = '03/21/2011';
$timestamp = strtotime($date);
$sqlDate = date('Y-m-d', $timestamp);
That should do what you need.
strtotime
date
$items=explode('/','03/21/2011');
$time=mktime(0,0,0,$items[0],$items[1],$items[2]);
$isodate=date('Y-m-d',$time);
While there are many ways to do this, I think the easiest to understand and apply to all date conversions is:
$date = date_create_from_format('n/d/Y', $date)->format('Y-n-d');
It is explicit and you'll never have to wonder about m/d or d/m, etc.
You can see it here
http://www.codegod.de/WebAppCodeGod/PHP-convert-string-to-date--AID597.aspx
Or use the Date class of PHP 5.3
STR_TO_DATE(created_at, '%m/%d/%Y') as 'Original Date Submitted'.
Answer 1:
You can use something like this
$dateStr = date('Y-m-d', strtotime($someDate));
Con
It is not great for code readability because it does not allow you to explicitly parse a certain format and make that obvious in the code. For instance your code will not be obvious to an outside programmer as to what format $someDate was in since strtotime parses multiple formats.
Pro
However if $someDate is subject to change and you want the code to continue to attempt to normalize various formats this is a great choice
Con
If you the data comes in a format that is not supported. For instance when trying to parse a date in a non-US date format meaning the month and day are switched but the format uses forward slashes (21/04/78) Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
Answer 2:
To really make your code clear as to which date you are parsing and to validate that the data coming in as using the correct format, I would use date_create_from_format. Here is some code to help:
$server_date_str='06-10-2013 16:00:09';
$server_date_time = DateTime::createFromFormat('d-m-Y H:i:s',$server_date_str);
// check the format
if ( !($server_date_time instanceof DateTime) ) {
$error_array = DateTime::getLastErrors();
throw new Exception( implode(" - ",$error_array['errors']) );
}
//convert DateTime object to Unix time stamp
$server_time = strtotime($server_date_time->format('d-m-Y H:i:s'));
//convert Unix timestamp to date string of the format 2012-10-21
$dateStr = date('Y-m-d', $server_time);
This example is explained in more full detail at this link:
http://boulderapps.co/parse-a-date-by-a-specific-date-format-in-php

Converting php date to fit mysql database

I want to convert an input date in the form of dd/mm/yyyy to the MySQL format which is yyyy-mm-dd.
I was trying to use date('Y-m-d', strtotime($_POST['date'])) but the problem is that the output is always Y-d-m, I think because it considers my 2nd argument to be mm/dd/yyyy.
How do I solve that?
date('Y-m-d', strtotime(str_replace('/', '-', $_POST['date'])))
From the manual:
Dates in the m/d/y or d-m-y formats
are disambiguated by looking at the
separator between the various
components: if the separator is a
slash (/), then the American m/d/y is
assumed; whereas if the separator is a
dash (-) or a dot (.), then the
European d-m-y format is assumed.
You need to convert your delimiters from / to -.
You could do:
$date = implode('-', array_reverse(explode('/', trim($_POST['date']))));
Reference: trim, explode, array_reverse, implode
(trim might not be necessary)
Mohamed,
I would recommend not even formatting the date in the database. If you store all of your date / time values as UNIX TIMESTAMP, you can format the data any way you want after you pull it from the data base.
Here's why: If all of your dates are formatted and you need to compare them, you'd need to bring them back to UNIX TIMESTAMP anyways. Yes, there are wheres to compare formatted date strings but its just one more extra step.
Although this is a bit late : If he uses timestamps then, in my experience he will run into trouble if he tries to perform any MySQL Date arithmetic / calculations on the timestamps - and the over head to do the same in PHP has the potential to become very expensive as it would involve selecting ALL records and then performing comparisons / calculations on the converted dates.
And I concur with jasonbar - PHP is looking at the delimiters of the date and considers it to be a US format date! He will need to run a str_replace('/','-',$_POST['date']) BEFORE using the date() function.
So, to fix this on an incoming request:
$mysqldate = date('Y-m-d', str_replace('/','-',strtotime($_POST['date'])));
So long as the data type for the target column is datetime anyways!
I found a pretty simple conversion.
$YOUR_DATE_FORMAT YYYY/MM/DD
$date = strtotime($YOUR_DATE_FORMAT);
$newdate = date('Y-m-d', $date); //or whatever format you choose.
works like a charm.

Categories