Date difference with custom format - php

I know there's a lot around here but for many articles I read and test this simply don't work..
I'm saving date with ACF like d.m.y and reading too.
When I make this type of comparison it works BUT only for the current month. No matter what I do, this is the working thing I've done that works, any advise please?
if(strtotime(date('d.m.y')) > strtotime($cd_date_from)) {
$output .= ' class="event-passed"';
}
This means that I'm hiding only the event on the table row that the date is older than today (showing today).
If the date is 15.03.19 or 28.03.19 it shows BUT if it's 15.04.19 (other month) it don't.
Thank you in advance

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.
http://php.net/manual/en/function.strtotime.php
Use:
if(strtotime(date('Y-m-d')) > strtotime($cd_date_from)) {
$output .= ' class="event-passed"';
}
and pass Y-m-d format values to $cd_date_from

it's much easier to use \DateTimeInterface to work with DateTime in php:
\DateTime::createFromFormat
<?php
$format = 'd.m.y';
$cd_date_from = '12.03.19';
$date = \DateTime::createFromFormat($format, $cd_date_from);
$date->setTime(0,0,0,0);
if (new \DateTime() > $date) {
echo 'hello';
}

Related

PHP Date strtotime

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

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

Current date is failing to format in PHP

I'm using the jquery datepicker, and when today's date is selected, it's failing to convert to the format I need for a database query.
The datepicker date format is 'm-d-Y', so today appears as 09-16-2013.
This part is working, and the datepicker correctly displays today's date as the default selection.
However, I need to use 'Y-m-d' format to query the database. This works fine when the date is less than today. But for today, it's failing and I'm getting 1969-12-31.
echo $enddt;
displays: 09-16-2013
I have tried:
echo date('Y-m-d', strtodate($enddt));
echo date('Y-m-d H:i:s', strtodate($enddt));
and neither works.
How do I format $enddt so it displays 2013-09-16 ?
The function is actually strtotime(), not strtodate():
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.
Since you have the date string separated by dashes, we'll need to convert it into slashes first to make strtotime() recognize the format as mm/dd/yyyy:
$enddt = '09-16-2013';
$enddt = str_replace('-', '/', $enddt);
echo date('Y-m-d', strtotime($enddt));
Demo!
$enddt = DateTime::createFromFormat('m-d-Y', '09-16-2013');
echo $enddt->format('Y-m-d');
See it in action

Codeigniter 2.1, MySQL - search by date

In my DB I have date field with a standard datetime for MySQL (YYYY-MM-DD HH:MM:SS). Trough AJAX request I am getting this time: DD/MM/YYYY
This is the function I had written to search trough DB:
$this->db->get_where('tvprogram', array('DATE(date)' => $date))->result_array();
At the moment this function isn't getting any data. What seems to be wrong here? How can I search and find all entries for specific day?
Use strtotime function to convert the date to correct format:
$date = date('Y-m-d', strtotime($date));
$this->db->get_where('tvprogram', array('DATE(date)' => $date))->result_array();
Please convert first posted date in database format and use with Date function in your searching field like this.
$date = date('Y-m-d', strtotime($search));
$this->db->where('DATE(created)',$date);
Check the format coming out of DATE(date) because it is probably like YYYY-MM-DD and the comparison will always fail.
Go into phpMyAdmin or similar and try SELECT DATE(now()) and double check the date format.
If $date has a format like DD/MM/YYY, then you can reformat it by using:
$date=date('Y-m-d',strtotime(strtr($date,"/","-")));
From the PHP manual (http://www.php.net/manual/en/function.strtotime.php):
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 fix the American/European date ambiguity, I simply replace "/" with "-" before the string to time conversion.

php date format inserting wrong date

I am confused as to why this piece of code does not convert a date in the UK format 00/00/0000 to mysql date format 0000-00-00. What i get in the db is 1970-01-01. It is in the date format not datetime so it should work? Thanks
$destroy = mysql_real_escape_string($_POST['destroy']);
$desttempdate=str_replace("-", "/", $destroy);
$destdate = date('Y-m-d', strtotime($desttempdate));
Here are a few options for you to get it working:
Something like this for PHP4:
function date2timestamp($date,$seperator='/'){
if($date!=''){
$dateEx = explode($seperator,$date);
$date = (strlen($dateEx[2])==2?'20'.$dateEx[2]:$dateEx[2]).'-'.$dateEx[1].'-'.$dateEx[0].' 00:00:00';
}
return $date;
}
For PHP5.3 use createFromFormat():
$date = DateTime::createFromFormat('j/M/Y', $UK_date);
echo $date->format('Y-m-d');
Also other options for createFromFormat() in PHP5.2 include:
PHP createFromFormat for 5.2 version
php dateTime::createFromFormat in 5.2?
DateTime::createFromFormat in PHP < 5.3.0
strtotime() function will return Unix timestamp and 0000-00-00 date does not fit into that - you will just get 0 (zero) instead, which will be converted properly, to 1970-01-01.
You can do what you want by doing something like that:
$destdate = mysql_real_escape_string($_POST['destroy']); // assuming YYYY/MM/DD
$destdate = str_replace('/', '-', $destdate);
if ($destdate != '0000-00-00'){
$destdate = date('Y-m-d', strtotime($desttempdate));
}
The problem is that you are passing to strtotime what it thinks is an invalid date. The documentation says:
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.
So what's happening here is that you are passing in a string using the / separator, which means that strtotime tries to parse it as m/d/y instead of d/m/y. Either do not do the replace at all if your date is in the european format, or better yet use DateTime::createFromFormat() as the docs suggest.
You can check that this is indeed the problem by checking the return value of strtotime:
$destroy = mysql_real_escape_string($_POST['destroy']);
$desttempdate=str_replace("-", "/", $destroy);
var_dump(strtotime($desttempdate));
This will output "bool (false)", confirming that strtotime fails to parse its input.
Solution:
As mentioned above, prefer DateTime::createFromFormat():
$date = DateTime::createFromFormat('d/m/Y', $_POST['destroy']);
$destdate = $date->format('Y-m-d');
Otherwise, even though I do not recommend this approach, the simplest way to fix the problem would be simply to skip the str_replace:
$destdate = date('Y-m-d', strtotime($_POST['destroy']));

Categories