I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
views:
3275answers:
7Converting from timestamp to format:
date('Y-m-d', $timestamp);
Converting from formatted to timestamp:
mktime(0, 0, 0, $month, $day, $year, $is_dst);
See date and mktime for further documentation.
When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. Check the MySQL Doc for TIMESTAMP info.
strtotime() and getdate() are two functions that can be used to get dates from strings and timestamps. There isn't a standard library function that converts between MySQL and PHP timestamps though.
Use the PHP Date function. You may have to convert the mysql timestamp to a Unix timestamp in your query using the UNIX_TIMESTAMP function in mysql.
A date string of the form:
YYYY-MM-DD
has no time associated with it. A MySQL Timestamp is of the form:
YYYY-MM-DD HH:mm:ss
to compare the two, you'll either have to add a time to the date string, like midnight for example
$datetime = '2008-08-21'.' 00:00:00';
and then use a function to compare the epoc time between them
if (strtotime($datetime) > strtotime($timestamp)) {
echo 'Datetime later';
} else {
echo 'Timestamp equal or greater';
}
You can avoid having to use strtotime() or getdate() in PHP buy using MySQL's UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(timestamp) FROM sometable
The resulting data will be a standard integer Unix timestamp, so you can do a direct comparison to time().
I wrote this little function to simplify the process:
/**
* Convert MySQL datetime to PHP time
*/
function convert_datetime($datetime) {
//example: 2008-02-07 12:19:32
$values = split(" ", $datetime);
$dates = split("-", $values[0]);
$times = split(":", $values[1]);
$newdate = mktime($times[0], $times[1], $times[2], $dates[1], $dates[2], $dates[0]);
return $newdate;
}
I hope this helps
function convert_datetime($datetime) { //example: 2008-02-07 12:19:32 $values = split(" ", $datetime);
$dates = split("-", $values[0]); $times = split(":", $values[1]);
$newdate = mktime($times[0], $times[1], $times[2], $dates[1], $dates[2], $dates[0]);
return $newdate; } i test this function is write work thank to help