I'm currently scraping content from a website using PHP and YQL. I need to convert an awkward date format into a UNIX timestamp so it can be formatted into a MySQL compatible date. I have tried using strtotime() but to no avail. Maybe a regular expression is the answer?
Examples of dates
08Dec10
06Aug10
29Jul10
07Jun10
04May10
Dan
If you are using PHP 5.3+
Then then DateTime::createFromFormat function is perfect for your needs..
$date = DateTime::createFromFormat('dMy', '08Dec10');
Then you can do whatever you want with the date, if you need it in a different format:
echo $date->format('Y-m-d');
If you are ever able to use the DateTime functions, several available from 5.2+ and more added in 5.3 then you should. Compared to the other functional solutions, the DateTime approaches are much more readable.
Also in all solutions, whether functional or using the DateTime object, check the return values. Both createFromFormat and strptime return false on error. So you can log the error and determine what the issue was.
Note: strptime is not available on Windows.
One solution is to use strptime:
$parts = strptime($str, '%d%b%y');
and then you can pass the values to mktime:
$timestamp = mktime(0,0,0,$parts['tm_mon']+1, $parts['tm_mday'], $parts['tm_year']+1900);
Break up the date components using substr and use strtotime to put it all together again.
<?php
strtotime('20'. substr($time, 5, 2). '-'. substr($time, 2, 3). '-'. substr($time, 0, 2));
?>
Related
I have a problem with verifying dates in PHP 5.2.17. I need the user to be able to enter the six digit date without any punctuation so Jan. 15, 2014 would be 011514. (This is due to input device limitation and for user convenience).
Tested and this is not working:
$testDate = "011514";
$myDate = date('mdy', strtotime($testDate));
echo $myDate;
I would expect that myDate is the same as test date but it's not, it prints out today's date 042314 (April 23, 2014)! PHP doesn't like that there is no punctuation in my original string. If I change $testDate = "01-15-14" then PHP spits out the correct string "011514".
How can I get strtotime() to understand that I want to check dates in 'mdy' format without using date_create_from_format ?
Extra info:
PHP version is 5.2.17 so date_create_from_format is NOT able to be used.
There's a limit to what strtotime() can understand. It can't understand everything. That's why they tell us what it does and we, as developers, need to write our code in a way that respects that.
All you need to do in your code is insert slashes and you're all set.
$testDate = "011514";
$date = sprintf('%s/%s/%s',
substr($testDate, 0, 2),
substr($testDate, 2, 2),
substr($testDate, 4, 2)
);
$myDate = date('mdy', strtotime($date));
echo $myDate;
Demo
Answering to your only question
How can I get strtotime() to understand that I want to check dates in 'mdy' format without using date_create_from_format ?
To get strtotime() to understand your format you need to download php sources, patch it so that it supported such a weird format and use your custom build.
Any one got a function to like strtotime() but the takes the format as input?
For example I need to convert yyyymmdd to a timestamp, or perhaps yyyyddmm. So I would like to specify the format used. Also Im on Windows so strptime() isn't an option.
PHP 5's DateTime class has the createFromFormat method which does what you need.
However, it requires PHP 5.3 so it's not always an option (yet).
Very easy to write a function, just take a look at mktime...
// Assumes yyyy-mm-dd
function fromdate($date) {
$d = explode("-", $date);
return mktime(0, 0, 0, $d[1], $d[2], $d[0]);
}
can anyone suggest the neatest way to do this comparison? I need to test if a date provided in dd/mm/yyyy format is less than a fixed date, e.g 01/05/2009 - I know I can convert these to unix time format using strtotime, then make the comparison, but I'm curious if there is a quicker way to do it - many thanks, just looking for a hint to improve my code!
One option is just to reverse the format - create a string of the form
yyyy/mm/dd
That's a sortable format, so you can just do an ordinal string comparison. Of course, this means you won't detect invalid data etc.
There's probably not a shorter way code wise, and I wouldn't bother optimizing this unless you're sure it's a bottleneck.
However, as long as you're sure it will always be the exact same format (including 2 digits for month and day and with 0s) you should be able to reorder the string to put the year first, then the month, and then the day, and then just compare the strings.
However, I'm not sure this would be faster than just letting the libraries convert to unix time and then comparing those.
If you can change the format that the dates are stored in, you could define them as yyyy/mm/dd and then just compare the strings.
I think that your solution of converting it to Epoch then doing a comparison is as fast and as clean as your going to get.
if you want to improve your code, I would suggest you to use DateTime class. It's been introduced in php 5.2.0 (so, it still might not be supported on all servers)
in php 5.3.0 you can write something like this:
$d1 = DateTime::createFromFormat('d/m/Y', '02/03/2009');
$d2 = DateTime::createFromFormat('d/m/Y', '02/05/2009');
$interval = $d1->diff($d2);
echo $interval->format('%R%d days');
Well, you could use the PHP date class, but I am not sure it would be any better than you current solution...
http://php.net/manual/en/book.datetime.php
use this method
yearmonthday
you have 01.05.2010 and 03.07.2010
and to compare : 20100501 <= or => 20100703
$fixedDate = '01/05/2009';
$variableDate = '28/04/2010';
// Now we do our timestamping magic!
$fixedDate = implode('', array_reverse(explode('/', $fixedDate)));
$variableDate = implode('', array_reverse(explode('/', $variableDate)));
if ($variableDate < $fixedDate) // 20100428 < 20090501
{
// there you go
}
To change 2009-12-09 13:32:15 to 09/12/2009
here:
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
You can use strtotime to get the timestamp of the first date, and date to convert it to a string using the format you want.
$timestamp = strtotime('2009-12-09 13:32:15');
echo date('d/m/Y', $timestamp);
And you'll get :
09/12/2009
[edit 2012-05-19] Note that strtotime() suffers a couple of possibly important limitations:
The format of the date must be YYYY-MM-DD; it might work in some other cases, but not always !
Also, working with UNIX Timestamps, as done with date() and strtotime() means you'll only be able to work with dates between 1970 and 2038 (possibly a wider range, depending on your system -- but not and illimited one anyway)
Working with the DateTime class is often a far better alternative:
You can use either DateTime::__construct() or DateTime::createFromFormat() to create a DateTime object -- the second one is only available with PHP >= 5.3, but allows you to specify the date's format, which can prove useful,
And you can use the DateTime::format() method to convert that object to any date format you might want to work with.
Using the date() method.
print date("d/m/Y", strtotime("2009-12-09 13:32:15"));
$long_date = '2009-12-09 13:32:15';
$epoch_date = strtotime($long_date);
$short_date = date('m/d/Y', $epoch_date);
The above is not the shortest way of doing it, but having the long date as an epoch timestamp ensures that you can reuse the original long date to get other date format outputs, like if you wanted to go back and have just the time somewhere else.
What is the best way in php to take the following string mm[some char]dd[some char]yyyy and translate it to yyyymmdd?
I will probably want in the future, according to local do the same with dd[some char]mm[some char]yyyy.
If there is a way that already uses the Zend Framework API, the better
<?php
$str = '08-24-1989'; // can be in any recognizable date format.
$new_str = date('Ymd', strtotime($str)); // produces "20090824".
?>
You can replace Ymd in the second statement above with any date format characters found here.
If you're looking to use Zend's Zend_Date framework, check out some examples and documentation here. Quite frankly though, the PHP functions are a lot simpler and easier to use in your case.
date('Ymd', strtotime($time));
Strtotime is absolutely the best tool to translate almost any time format into a standard one that you can then use Date to put into the format you want.
Because you question title says MySQL Dates, this is the string format that mysql uses.
date('Y-m-d h:i:s', strtotime($time));
Unless [some char] varies , use the mysql str_to_date function, e.g. STR_TO_DATE('12|23|2009','%m|%d|%Y');
I would absolutely use TIMESTAMP for any date storage. It's incredibly easy to handle time differences (like SELECT ... WHERE date BETWEEN 2138728753 AND 376251237) and can be translated to any locale pretty easily :)