Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert unixtimestamp to mysql date format

I'm writing code to subtract two dates. It is for a contract type thingy, where user gets to see the number of days left for his contract to complete. Something like start_date_time="today" and end_date_time=y where the value of y is retrieved from the database (DATETIME type). It is in the mysql datetime format (yyyy-mm-dd HH:mm:ss).

<?php
include_once '../include/connections.php';
$id =$_REQUEST['uid'];
$result= mysql_query("SELECT * FROM data WHERE uid  = '$id'");
$test = mysql_fetch_array($result);
echo $test[14];
echo "<br /><br />";
$today=time();
$enddate=strtotime('$test[14]');
$timediff = $enddate - $today;
$days=intval($timediff/86400);
$remaining=$timediff%86400;
$hours=intval($remaining/3600);
$remaining=$remaining%3600;
$mins=intval($remaining/60);
$secs=$remaining%60;
echo "<br>".$days.' days '.$hours.' hours '.$mins.' minutes and '.$secs.' seconds.';
?>

When I echo $test[14];, I get the date and time as stored in the database which is (2012-09-26 00:00:00)

When i echo $today; then i get it in this format 1348381896. Now, how do i convert this format to the one retrieved from the db so that i can subtract the 2 dates and get the number of days and time left?

like image 986
user1691915 Avatar asked Dec 30 '25 09:12

user1691915


1 Answers

You can use these 2 functions to convert dates to each other,

Use this for timestamp to MySQL datetime:

$timestamp = '1348381896';
$date = date('Y-m-d H:i:s', $timestamp);
echo $date;

Use this one for MySQL datetime to timestamp:

$date = '2012-09-26 00:00:00';
$timestamp = strtotime($date);
echo $timestamp;

Also if you are willing to Subtract your dates in MySQL side, you can use the DATEDIFF and or TIMEDIFF functions:

Also you can work with timestamps in MySQL too, using TIMESTAMPDIFF and UNIX_TIMESTAMP functions ...

like image 139
Night2 Avatar answered Jan 01 '26 23:01

Night2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!