Converting TIMESTAMP to unix time in PHP? - php

Currently I store the time in my database like so: 2010-05-17 19:13:37
However, I need to compare two times, and I feel it would be easier to do if it were a unix timestamp such as 1274119041. (These two times are different)
So how could I convert the timestamp to unix timestamp? Is there a simple php function for it?

You're looking for strtotime()

You want strtotime:
print strtotime('2010-05-17 19:13:37'); // => 1274123617

Getting a unixtimestamp:
$unixTimestamp = time();
Converting to mysql datetime format:
$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);
Getting some mysql timestamp:
$mysqlTimestamp = '2013-01-10 12:13:37';
Converting it to a unixtimestamp:
$unixTimestamp = strtotime('2010-05-17 19:13:37');
...comparing it with one or a range of times, to see if the user entered a realistic time:
if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}
Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:
if(ctype_digit($_GET["UpdateTimestamp"]))
{...}

If you're using MySQL as your database, it can return date fields as unix timestamps with UNIX_TIMESTAMP:
SELECT UNIX_TIMESTAMP(my_datetime_field)
You can also do it on the PHP side with strtotime:
strtotime('2010-05-17 19:13:37');

if you store the time in the database, why don't you let the database also give you the unix timestamp of it? see UNIX_TIMESTAMP(date), eg.
SELECT UNIX_TIMESTAMP(date) ...;
databases can also do date and time comparisons and arithmetic.

Related

Formatting the time hh:mm:ss.0000000 to hh:mm not working

I am using MsSQL in PHP. I am storing the time in database table row with datetime as datatype.The time is stored like this :08:30:00.0000000.I need the time to be displayed in 08:30.I have used
date('h:i', $time_value); // $time_value stores the time value
This formats the date and gives the result in 4:00. Any formatting is required to display the correct time stored in database?
The PHP date function does not expect a Mysql datetime as second parameter but you do so:
date('h:i', $time_value);
^
|
second parameter
This is the reason why it does not work. You're using the wrong value, convert the database value into a timestamp first because the date function needs a timestamp. As you migh imagine, this has been done before, here is just a selection of related Q&A material:
MySQL convert datetime to unixtime?
MySQL convert datetime to Unix timestamp
Alternatively just use a string function like substr to obtain the string you're looking for:
$time_value = '08:30:00.0000000';
echo substr($time_value, 0, 5); # 08:30
Demo: https://eval.in/146148
You can do the conversion / formatting with the SQL statement already, a related example is given in:
How to display time in HH:MM format?
You can also use:
date('h:i', strtotime('08:30:00.0000000'));
In your case:
date('h:i', strtotime($time_value));

PHP: how to create date before the Epoch (1970) using Date instead of DateTime?

In my PHP script I've got a function handling birthdays like so:
$dateTime = \DateTime::createFromFormat('U', $time);
The problem is that this returns false with negative $time numbers (i.e. dates before 1-1-1970). In the PHP docs there's a comment saying that indeed
Note that the U option does not support negative timestamps (before
1970). You have to use date for that.
I'm unsure of how to use Date to get the same result as DateTime::createFromFormat() gives though. Does anybody have a tip on how to do this?
If you just need to format a UNIX timestamp as a readable date, date is simple to use:
// make sure to date_default_timezome_set() the timezone you want to format it in
echo date('Y-m-d H:i:s', -12345);
If you want to create a DateTime instance from a negative UNIX timestamp, you can use this form of the regular constructor:
$datetime = new DateTime('#-12345');

Converting PHP String having a unix timestamp value to a MySQL Timestamp value

I am setting a Database value within from a PHP file. In php file i have a string variable which stores unix timestamp value.
MySql table i am having is having a schema where i have to store these timestamp values in login field which is of timestamp datatype.
i tried sending
date('Y-m-d G:i:s', strtotime($userLogin));
to my database but all it stores is 0000-00-00 00:00:00
MySQL has FROM_UNIXTIME() function for this.
MySQL provides the FROM_UNIXTIME( ) and UNIX_TIMESTAMP( ) functions to converta Unix timestamp to a MySQL date format, and vice versa.
Example:
$sql = "INSERT INTO yourtable(date, ..., ...) VALUES (FROM_UNIXTIME($yourdate), ..., ...)";
strtotime () is intended for converting strings in various date formats into UNIX timestamps. If the string is a timestamp already then it won't look like a meaningful formatted date/time to strtotime () and it will fail.
If the string is already a timestamp, then you don't need to do anything more to it than cast it to integer (strictly speaking even that step shouldn't be necessary, but casting will strip out any non-numerical characters, so it doesn't usually hurt to cast)
Additionally, MySQL is capable of parsing UNIX timestamps (with FROM_UNIXTIME(), I think, I'd have to look it up to be sure)
If $userLogin holds timestamp value than you don't need to use strtotime(),
For example, this one should work -->
$userLogin = time();
date('Y-m-d G:i:s', $userLogin);
I had to add
$login = date('Y-m-d H:i:s',(int)($userLogin/1000));
and it worked...

UTC datetime conversion

The values that I received from my device are: 090211 = ddmmyy and 062123 = hhmmss in UTC.
But I found that the time is always 8 hours later if compared to the time that I need. It is because the time for Malaysia is +8:00. First I would like to add 8 hour, and finally I would like to store this kind of date format into my MySQL database as "2011-02-09 06:21:23". How would I convert these values?
To convert in PHP to a datetime, you will need the function DateTime::createFromFormat(); This function will return a DateTime.
Using this function you can also pass the timezone as a parameter.
Example:
$date = DateTime::createFromFormat( 'dmy Gms', '090211 062123', new DateTimeZone("Europe/Amsterdam") );
You can create a output a following:
echo $date->format('Y-m-d H:i:s');
or UNIX timestamp for the MySQL:
echo $date->format('U');
Hope this helps!
PHP has both localtime and gettimeofday functions, are you by chance using the wrong one (or misinterpreting its results)?

Formatting an SQL timestamp with PHP

I have a mySQL database with a timestamp field. It currently only has one entry while I'm testing, it is
2010-02-20 13:14:09
I am pulling from the database and using
echo date("m-d-Y",$r['newsDate'])
My end result is showing as
12-31-69
Anyone know why?
Edit:
editedit:
disregard that edit... the FTP addon for notepad++ timed out and unfortunately doesn't display an error when it can't synch.
The date function expects an UNIX timestamp as its second parameter -- which means you have to convert the date you get from the DB to an UNIX timestamp, which can be done using strtotime :
$db = '2010-02-20 13:14:09';
$timestamp = strtotime($db);
echo date("m-d-Y", $timestamp);
And you'll get :
02-20-2010
You were passing the '2010-02-20 13:14:09' string to the date function ; that string is not a valid UNIX Timestamp.
'12-31-69' is probably 1970-01-01, in your locale ; and 1970-01-01 is the Epoch -- the date that corresponds to the 0 UNIX Timestamp.
For starters, the php date() function is expecting seconds as the second variable. So that accounts for why your date is displaying wrong. Check this source on that issue.
Which then provides us the answer to the problem, to get PHP to format the date from a SQL timestamp correctly, we just change the query a tad...
SELECT author, `when`
Change it to...
SELECT author, UNIX_TIMESTAMP(`when`)
Then use the PHP date function, with the variable that is storing the result of that above SQL query.
You could just use MySQL's date_format() function instead:
SELECT date_format(timestampfield, '%m-%d-%Y') FROM table etc....
This will save you having to round-trip your timestamp into unix time and then back into a normal date string in PHP. One datetime formatting call rather than two.
i think this will be useful to newble:
example basic subtraction 1 hour from date from MYSQL format:
$to='2013-25-10 22:56:00'; //curr time
$timestamp = strtotime($to); //convert to Unix timestamp
$timestamp = $timestamp-3600; //subtract 1 hour (3600 this is 1 hour in seconds)
echo date("Y-m-d H:i:s",$timestamp); //show new date
EDIT: After checking, it appears that MySQL returns a timestamp as a string to PHP, so this answer was bogus :)
Anyway, the reason you get a date in 1969 is probably that you're converting a zero unix time from UTC to localtime. The unix time is the number of seconds since 1970. So a value of 0 means 1970. You probaby live in a timezone with a negative offset, like GMT-6, which ends up being 31-12-69.
ok, I was wrestling with this for a week (longer but i took a break from it).
I have two specific fields in tables
creationDate > timestamp > current_timestamp
editDate > timestamp > current_timestamp
they were pulling out either dec 31 1969, or just nothing... annoying... very annoying
in mysql query i did:
unix_timestamp(creationDate) AS creationDate
unix_timestamp(editDate) AS editDate
in php convert i did:
$timestamp = $result_ar['creationDate'];
$creationDate = date("Y-M-d (g:i:s a)", $timestamp)
echo($creationDate);
$editstamp = $result_ar['editDate'];
$editDate = date("Y-M-d (g:i:s a)", $editstamp)
echo($editDate);
this solved my problem for me returning
2010-Jun-28 (5:33:39 pm)
2010-Jun-28 (12:09:46 pm)
respectively.
I hope this helps someone out..

Categories