I currently have a date that's being stored in my SQL database as a VARCHAR of 255 characters. I declared this string as
//within an object...
$date = date(DATE_RFC822);
Now, later on in the coding, I realise that I need to actually compare dates with each other. My initial, very naive attempt looked a little bit like this:
if(object_1->date > object_2->date){
//do this that assumes that object_1 was created at a later date than object_2
}else{
continue;
}
While this worked fine for different times of the same day; using the code a week later began to show significant bugs.
strtotime() converts a string into unix time (an integer) which can easily be compared with other unix time values. If you are running PHP 5.2.8 or greater, you could also make use of the DateTime class which are relatively easy to compare (see this question for more info)
You can't compare dates in DATE_RFC822 format with each other. You should use Date or DateTime fields in MySQL and DateTime or Unix timestamps in PHP. It's safe to use your DATE_RFC822 string in the PHP DateTime constructor or in strtotime(). (Still, if you use Date or DateTime in MySQL you can also sort by date and search by date, etc.)
PHP DateTime objects can be compared with each other like normal PHP variables, so you can do $date1 < $date2 to determine if $date1 is before $date2.
Related
How do you convert an input date like 01/16/2013 to a time format similar to 1422424719. Whats the best way to compare these two time stamp.
$timestamp = strtotime('01/16/2013');
Just compare them as you would do with any other variable. <, >, = ... are all available
Also check the PHP manual for the DateTime class. It will make handling dates and times easier.
I want to ask about changing a datetime value of PHP with datetime value from MySQL data.
I have try to do this at PHP:
$sitgl = date('Y-m-d', strtotime(2012-01-12));
$sijam = date('H:i:s', strtotime(13:00:00));
$awal = $sitgl.' '.$sijam;
$awal2 = date('Y-m-d H:i:s', strtotime($awal));
$debrangkat = strtotime($awal2);
And I'm trying to convert same datetime at MySQL like this (convert it to seconds):
SELECT date_start_book, time_start_book, (TO_DAYS(CAST(date_start_book AS DATE))*86400) + TIME_TO_SEC(CAST(time_start_book AS TIME)) FROM `t_request_queue` WHERE `request_id` = '1301-0087'
which is date_start_book value is 2012-01-12 and time_start_book value is 13:00:00
My question is: why the PHP code return value : 1357970400 but the MySQL value return 63525214800 ?
what must I do to make both of value is same? Is strtotime() not return a seconds or why?
First of all as others have suggested that php code is really hurting brain. You could make that Unix Timestamp in just one line. But to answer your real question. MYSQL TO_DAYS works different than PHP UNIX Timestamp
According to MySQL Website
Given a date date, returns a day number (the number of days since year 0).
mysql> SELECT TO_DAYS(950501);
-> 728779
mysql> SELECT TO_DAYS('2007-10-07');
-> 733321
TO_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it does not take into account the days that were lost when the calendar was changed. For dates before 1582 (and possibly a later year in other locales), results from this function are not reliable
And according to PHP Website timestamp is
Returns the current time measured in the number of seconds since the
Unix Epoch (January 1 1970 00:00:00 GMT).
And hence the difference in two values. Their starting point is way too distant from each other. MySQL starts from year 0 and PHP starts from year 1970.
Suggestion
I would suggest you save php's timestamp in mysql rather than a formatted date time. This will help you stay consistent and allow you to perform any date or time comparisons easily.
Finally, I change the PHP to datetime and at query I'm using ADD_DAYS to add a date with a seconds then I compare it with the PHP datetime result.
So many thanks to all contributor.
SQLite doesn't have a data type for dates.
I was wondering if it's enough to make string comparisons between date strings like Y-m-d H:i:s (the standard sql datetime format).
For example ...WHERE date < NOW().... would this fail in certain situations?
You can store dates in SQLite with the following data types:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
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.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
You can then convert these fake dates using the functions listed here.
Now, you also mentioned function NOW() and that won't work in SQLite. That's for MySQL. This will show you SQLite syntax to use:
sqlite> select date('now');
2012-02-12
sqlite> select date('now') = date('2012-02-12');
1
sqlite> select date('now') = date('2012-02-11');
0
So, it is highly recommended for you to use this functions and, on the other side, make sure you don't use NOW().
Quoted From Roger
SQLite doesn't have dedicated datetime types, but does have a few
datetime functions. Follow the string representation formats (actually
only formats 1-10) understood by those functions (storing the value as
a string) and then you can use them, plus lexicographical comparison
on the strings will match datetime comparison (as long as you don't
try to compare dates to times or datetimes to times, which doesn't
make a whole lot of sense anyway).
Depending on which language you use, you can even get automatic
conversion. (Which doesn't apply to comparisons in SQL statements like
the example, but will make your life easier.)
Personally I like using unsigned INT and unix timestamps for dates. It is very easy and efficient to compare dates as integers, and PHP has numerous functions for making these dates human readable.
http://php.net/manual/en/function.date.php
Using now() won't work because SQLite doesn't know what the means. SQLite does, however, know what current_timestamp means and that has the desired format:
The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".
In MySQL, current_timestamp is a synonym for now() and that also has the desired format:
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'.
So they both use ISO-8601 timestamp formats and just about any database will be able to convert between ISO-8601 strings to and timestamps quite easily so that is a good and portable choice.
I'm pretty certain it would fail in certain situations.
A faster method would be storing time() values (or mktime()) and generating queries based on time().
This would also work with MySQL.
In my php application I have this code:
<?php echo date("d/m/ Y ",strtotime($row["m_date"]));?>
In it, $row["m_date"] is fetching from a database.
The problem is that all the dates are printing perfectly except 27/2/2011. It's printing 1/1/1970 instead.
The date in the database is fine, and prints correctly in a PDF.
I'll assume you're getting the date from the database as the string 27/2/2011 because that's most probably what happens (correct me if I'm wrong).
PHP considers the string 27/2/2011 as being in the m/d/Y format, not d/m/Y and tries to parse under that assumption. Because the date is not valid under that format strtotime returns false. Giving false as the timestamp parameter to date is taken as 0, which is the timestamp for January 1st 1970.
What you need to do is either get your date in another format (or better still, as a timestamp) from the database, or parse it yourself (say using explode).
Good luck,
Alin
The database should be able to return the date to you as a UNIX timestamp. For example, MySQL has the UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(date_column) FROM table;
Postgres has date_part
SELECT DATE_PART('epoch', date_column) FROM table;
Most other databases should have similar features. If you can get the date out as a UNIX time stamp you can pass that directly to date() without having to use strtotime() as well.
All of this does of course assume you're using a temporal datatype for the columns in question (timestamp, datetime, timestamp with time zone, etc) and not just storing a string. You are using a temporal type, right? If not, then why not?
if you are storing the date in the database as a timestamp this should work
<?php echo date("d/m/Y",$row["m_date"]);?>
if you are storing the date in the database as a date or datetime this should work
<?php echo date("d/m/Y",strtotime($row["m_date"]));?>
How is the m_date stored in the databases? Is it a datetime object? Or a string.
Problem with strtotime is that it isn't real good at deciphering written dates. So something like 27/2/2011 gives problems while 27/02/2011 gives no problems at all.
So there are 2 solutions:
Make sure all the dates that get entered into the database are of the correct format (dd/mm/yyyy).
Write a regular expression that adds a leading zero to all single characters.
Why is the timestamp generated by the PHP time() function so different from SQL datetime?
If I do a date('Y-m-d', time()); in PHP, it gives me the time now, as it should. If I just take the time() portion and do:
$now = time();
//then execute this statement 'SELECT * FROM `reservation` WHERE created_at < $now'
I get nothing. But hey, so if the value of $now was 1273959833 and I queried
'SELECT * FROM `reservation` WHERE created_at < 127395983300000000'
then I see the records that I have created. I think one is tracked in microseconds vs the other is in seconds, but I can't find any documentation on this! What would be the right conversion between these two?
The time() function doesn't return microseconds, so it should work if you're using the correct datatype. But you have 2 different datatypes right now, INT and a date field (could be DATE/DATETIME/TIMESTAMP). If you want to compare a date in the database to a timestamp as integer, you could use something like:
SELECT * FROM Tbl WHERE UNIX_TIMESTAMP(date) < $timestamp;
time() gives a Unix timestamp (seconds passed since 01-01-1970) - SQL wants to have timestamps in format YYYY-mm-dd hh-ii-ss which is done by date() - so if you don't want to call 2 PHP functions, just use $now = date("Y-m-d H:i:s") or, better, change your SQL query to created_at < NOW().
They're just 2 different ways of storing dates, each with their advantages and disadvantages. You can use MySQL's date field, or simply store unix timestamps in an INT field. You can also use:
SELECT UNIX_TIMESTAMP(field_name) FROM ...
to return a date field as a Unix timestamp.
The MySQL date field is human-readable and can store any date in the foreseeable future. However, it does not store timezone information which can cause serious issues if not handled correctly. Facebook had this problem a while back.
Unix timestamps store timezone information (since it's defined as the number of seconds since 12:00am January 1st 1970 UTC). Comparison operations are faster on integers, and PHP's time/date functions are designed to be used with Unix timestamps. However, Linux can only support dates from 1902 to 2038 and on Windows from 1970 to 2038. MySQL and architecture in general will switch to 64-bit integers long before 2038 arrives, but if you need to store dates that are in the distant future or past, Unix time isn't for you.