How to convert MySQL TIMESTAMP to date time in PHP - php

I have a MySQL DB table with a column named "timestamp", a type of timestamp, and attribute of on update CURRENT_TIMESTAMP and a default of CURRENT_TIMESTAMP.
If I add a record to the table, specifying other values, but not the timestamp, then the timestamp is automatically added like 2016-12-28 17:02:26.
In PHP I query the table using the following query
SELECT * FROM history WHERE user_id = 9 ORDER BY timestamp ASC
The result of the query is saved into $rows and I use a foreach to create an array with some of the other values formatted. I am attempting to format the time stamp to UK type 24-hour date time: dd/mm/yy, HH:MM:SS.
I have tried both the date() and strftime() functions as follows:
$formatted_datetime = strftime("%d %m %y %H %M %S", $row["timestamp"]);
$formatted_datetime = date("d/m/y, H:i:s", $row["timestamp"]);
Both of these result in the following notice and the date time being output incorrectly like 01 01 70 00 33 36:
Notice: A non well formed numeric value encountered in /home/ubuntu/workspace/pset7/public/history.php on line 20
I am new to PHP and MySQL and so far none of the other questions or documentation I have seen have successfully addressed performing this conversion.I do not understand why strftime() does not work, nor how to do this properly?

To do this the OO (and most flexible) way use DateTime class and use the static createFromFormat method to instantiate a new DateTime object:
$new_datetime = DateTime::createFromFormat ( "Y-m-d H:i:s", $row["timestamp"] );
Now you can use the $new_datetime object to generate any string representation you'd like by calling the object's format method:
echo $new_datetime->format('d/m/y, H:i:s');
To boot, you since you've a DateTime object you can now also to any manner of transformation (like shifting timezones or adding days), comparison (greater or less than another DateTime), and various time calculations (how many days/months/etc... between this and another DateTime).
DateTime:http://php.net/manual/en/class.datetime.php
Learn it. Love it. Live it.

Normally in MySQL date timestamp save time as YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14) formate you can easily convert them as your wish using date formate but have to convert your input to time first. Following will do the trick
$formatted_datetime = date("d/m/y, H:i:s", strtotime($row["timestamp"]));

Why not make MySQL do the work? And do you really want mm/dd/yy, not dd/mm/yy?
SELECT *, DATE_FORMAT(timestamp, '%m/%d/%y, %T') formatted_date FROM ....
Then you can extract the formatted date as $row['formatted_date'].
See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
echo $row['date'] . "
";
}
The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.
Here are some other sample date output formats that may be of practical use:
echo date("F j, Y g:i a", strtotime($row["date"])); // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"])); // 10.05.08
echo date("j, n, Y", strtotime($row["date"])); // 5, 10, 2008
echo date("Ymd", strtotime($row["date"])); // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"])); // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"])); // Sun Oct 5 21:34:02 PST 2008

I would use the Carbon class and its String Formatting
$carbon = Carbon::instance('2016-12-28 17:02:26');
Then you can format it the way you want.

Related

Convert SQLite to MySQL datetime

I have SQLite DB one table contains datetime field
with datatype "timestamp" REAL value is 18696.0
attach image for table structure
So, I want this 18696.0 value to be converted into MySQL Y-m-d format and result should be 2021-03-10
I have didn't found any solution online. any help would be appreciated.
SQLite timestamp converted into MySQL timestamp.
EDIT: Thankyou for updating your question with the correct number and what date it should represent.
You can achieve what you need with a function that adds the days onto the Unix Epoch date:
function realDateToYmd($real, $outputFormat='Y-m-d')
{
$date = new DateTime('1970-01-01');
$date->modify('+' . intval($real) . ' days');
return $date->format($outputFormat);
}
echo realDateToYmd('18696.0');
// returns 2021-03-10
SQLite dates stored in REAL data type stores dates as a Julian Day.
From https://www.sqlite.org/datatype3.html
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
PHP has a jdtogregorian function, in which one comment has a handy function to convert to ISO8601 dates:
function JDtoISO8601($JD) {
if ($JD <= 1721425) $JD += 365;
list($month, $day, $year) = explode('/', jdtogregorian($JD));
return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
echo JDtoISO8601('17889.0');
// Results in -4664-11-16
The results don't exactly look right, is it definitely 17889.0 in SQLite?
If this float number 18696.0 represents the number of days since 1970-01-01 then the date can also be calculated like this:
$days = 18696.0;
$dt = date_create('#'.((int)($days * 86400)));
$mysqlDate = $dt->format('Y-m-d'); //"2021-03-10"
background information
Or simply with gmdate:
$mySqlDate = gmdate('Y-m-d',$days*86400);
The days are simply converted into seconds to get a valid timestamp for gmdate.
Try this:
<?php
echo date('Y-m-d H:i:s', 17889);
?>
Output:
1970-01-01 04:58:09

Convert excel decimal number into date

I have a number on which after applying some formula I got 43917.60417. Excel convert this number into date and datetime format as 3/27/2020 14:30:00. How can I convert this number into date or datetime using mysql or php. I searched a lot but didn't got any solution.
I tried
SELECT FROM_UNIXTIME(REPLACE('13577.77916', '.', ''));
-- this results in 2013-01-10 06:01:56
SELECT FROM_UNIXTIME(REPLACE('43917.60417', '.', ''));
-- this results in null
Here you go in PHP
<?php
$unix = (43917.60417 - 25569) * 86400; //convert to unix first
echo gmdate("d-m-Y H:i:s", $unix); //return to your desired date format
?>
AND IN MySQL, This should work for both positive and negative epoch
SELECT DATE_ADD(FROM_UNIXTIME(0), interval (13577.77916-25569)*86400 second);
And to specify date format in MySQL, you can use DATE_FORMAT(
SELECT DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), interval (13577.77916-25569)*86400 second),'%Y-%m-%d') as my_new_date;
The DateTime extension dt knows a special method createFromMsTimestamp for the MS Excel timestamp.
$excelTimestamp = 43917.60417;
$date = dt::createFromMsTimestamp($excelTimestamp);
echo $date->format('Y-m-d H:i:s');
//2020-03-27 14:30:00

Reduce 100 years from a given date in php

$date_raw = '05/05/1995';
$newDate = (date('j F Y', strtotime('-192years -14months -2days', strtotime($date_raw))));
print "New Date: $newDate <br>";
I'm trying to subtract 100+ years from a given date. but the value i get is real till 92 years only. after that i don't get correct subtraction. whats the reason?
If you need to work with dates that fall outside the range of a 32-bit signed unix timestamp (1901-12-13 to 2038-01-19), then start using DateTime objects
$date_raw = '05/05/1995';
$newDate = (new DateTime($date_raw))
->sub(new DateInterval('P192Y14M2D'))
->format('j F Y');
echo $newDate, PHP_EOL;
gives
3 March 1802
or you can do this in the following way
// set your date here
$mydate = "2018-06-27";
/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastHundredyear = strtotime("-100 year", strtotime($mydate));
// format and display the computed date
echo date("Y-m-d", $lastHundredyear);
this will give you following output
1918-06-27

PHP TIME converting?

I have something in my database that shows the time when the users who signed up on my recorded .. When the person makes the user saves the script (time ();) currently in the database under the variable name "REGTIM".
If I use echo to print it out, I get for example:
     1375202508
How can I make this a date if it is possible? or for example as mentioned below.
for example: 08/06/2013 2:11
You can use date() function with timestamp mention in the second argument,
date ( string $format [, int $timestamp = time() ] )
or in your case:
date('m/d/Y H:m', 1375202508);
you can read more on http://php.net/manual/en/function.date.php
You could have got the answer to that with a little bit of searching. But here you go:
echo date('m/d/Y h:m', 1375202508); // 07/30/2013 10:07 -- 12-hour format
echo date('m/d/Y H:m', 1375202508); // 07/30/2013 22:07 -- 24-hour format
See the documentation for more options: http://php.net/manual/en/function.date.php
that's probably just a unix timestamp, so use FROM_UNIXTIME() and DATE_FORMAT() to do the conversion/formatting inside your query, or use date() in PHP to work with the timestamp directly.
e.g.
echo date('d/m/Y h:m', $timestamp)
or
SELECT DATE_FORMAT('%d/%m/%y %h:%m', FROM_UNIXTIME(REGTIM))

Date conversion and updating mongodb document using PHP

Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php

Categories