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']));
Related
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.
I used the following code to convert date in php, but I am getting wrong date after the conversion. I used CURRENT_TIMESTAMP as default value in my database table.I am passing "date" variable from javascript.
Can anyone please solve this problem. Thanks in advance.
$date1=mysql_real_escape_string($data->date);
print_r($date1) // This is one displaying the right date.
$date=strtotime($date1);
$timedatenew=date('Y-m-d H:i:s', $date);
print_r($timedatenew) // This is displaying the date like "1970-01-01 01:00:00".
As u said u have date in format dd/mm/yy try with this
$timedatenew= date("Y-m-d H:i:s",strtotime(str_replace('/', '-', $date ))));
it convert / to -
You are getting wrong date because when you use date('Y-m-d',strtotime($date)) for converting date format then 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. Check detail here: php.net/manual/en/function.strtotime.php
(above part is commented by hjpotter92 in same this type of other question)
if you want exact right format then use DateTime object, it can format the date from any string format, it also works well with other formatter other than - like / or .
that means you can change date format from:
d/m/Y or d-m-Y or d.m.Y to your any desired format like Y-m-d.
$date = DateTime::createFromFormat('d/m/Y', "12/07/2019");
echo $date->format('Y-m-d');
// output: 2019-07-12
see below examples from the php official doc DateTime::createFromFormat
Example DateTime::createFromFormat()
Object oriented style
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>
Procedural style
<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2009-02-15
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
This question already has answers here:
PHP Date String Format [duplicate]
(2 answers)
Closed 3 years ago.
I am trying to convert a date from dd/mm/yyyy => yyyy-mm-dd. I have using the mktime() function and other functions but I cannot seem to make it work. I have managed to explode the original date using '/' as the delimiter but I have no success changing the format and swapping the '/' with a '-'.
Any help will be greatly appreciated.
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. Check more here.
Use the default date function.
$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );
EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
Try Using DateTime::createFromFormat
$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');
Output
2012-04-24
EDIT:
If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.
$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
OUTPUT:
2010-4-5
Here's another solution not using date(). not so smart:)
$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
I can see great answers, so there's no need to repeat here, so I'd like to offer some advice:
I would recommend using a Unix Timestamp integer instead of a human-readable date format to handle time internally, then use PHP's date() function to convert the timestamp value into a human-readable date format for user display. Here's a crude example of how it should be done:
// Get unix timestamp in seconds
$current_time = date();
// Or if you need millisecond precision
// Get unix timestamp in milliseconds
$current_time = microtime(true);
Then use $current_time as needed in your app (store, add or subtract, etc), then when you need to display the date value it to your users, you can use date() to specify your desired date format:
// Display a human-readable date format
echo date('d-m-Y', $current_time);
This way you'll avoid much headache dealing with date formats, conversions and timezones, as your dates will be in a standardized format (Unix Timestamp) that is compact, timezone-independent (always in UTC) and widely supported in programming languages and databases.
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