Unix timestamp vs datetime [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Datetime vs Timestamp?
I have a Mysql table, which has a column add_date. It tracks the date/time when the record was added to the database.
Queries based on this table:
Display when the record was added in the format: 2 hours ago, 4 weeks ago, 1 year ago etc
Allow users to search records inserted in any day/month/year. So the user may be allowed to choose to see the records inserted in 2009 only.
Which would be better in this case - unix timestamp or datetime?
Right now I'm using both, but since the table will have millions of records over time, having both columns may affect the size of the database.
Unix timestamp seem to be better for conversion to 2 hours ago format in PHP and also it is timezone independent. But datetime has better readability and making a query for a particular date/time/year seems easier.
Your suggestion?

When you have the choice, I'd say go for mySQL dates.
You won't have to take care of date range issues
You can easily query time spans using mySQL's date functions (BETWEEN(), DATE_ADD etc.)
Date related queries will be much faster, especially when you have millions of records, because you won't have to use FROM_UNIXTIME() which can be expensive in large queries
It's child's play to convert DATE fields into UNIX timestamps when necessary.

I'd go for the mysql formats, just because mysql has a plenty of datetime function, to use which with timestamp will cost you another conversion.
but since the table will have millions
of records over time, having both
columns may affect the size of the
database.
oh my.
are you really concerned in 4 additional megabytes of space?

You can get the best of both worlds by using a unix timestamp and the MySQL from_unixtime() function to convert the result to datetime format where needed.

Related

Php and mysql date and time

I am new in php and I saw some programmer store datetime in database by php date() or mysql NOW() or take column as timestamp. I want to know that the difference between these three is and also how to convert these three formats to users local time worldwide.
As per the mysql's law you can have only one timestamp field,no
restrictions for having number of datetime field..
You can set the
timestamp field for onupdate current timestamp or current
timestamp..And these field type not affecting the date insert
method..
If you are using date() function you can set your own
date format..But not in the now()
For date format the syntax check this article https://www.w3schools.com/php/func_date_date.asp
Finaly Datetime and timestampis mysql
date() and NOW()is php
There's a few things to consider:
TIMESTAMP columns are limited to dates between 1931 and 2038, as they're 32-bit timestamp values.
DATETIME columns can go up to the year 9999. While they don't auto-populate like TIMESTAMP values do by default, they're less restricted, you can have as many as you want per table.
When inserting times your PHP clock and your database clock might differ slightly. Using NTP can help narrow that gap, but drifts do happen. PHP's date() function requires formatting into ISO-8601 format for inserting (YYYY-MM-DD HH:MM:SS). The MySQL NOW() function does not, same with UTC_TIMESTAMP().
I strongly recommend using UTC time in your database for a few reasons:
If you store in local time you'll need to store the time-zone as well, and those can change in wild and bizarre ways.
You may need to accommodate other time zones in the future, which means you might have multiple local times in your data where each record might have a different meaning from others.
Your server might get moved between time-zones which can shift all your data.
So store with UTC and render out as local times based on the user's time-zone preference or some sensible default for your application. Remember, time formatting is often a fussy thing, every country has different date formatting standards, and even a single country might have multiple preferences for long-form, short-form, or numerical forms.

SQL - Best way to record multiple date/times and compute time difference.

I'm currently working on a project where I'm recording times into my database, and I want to store the difference between the two times as well. I implemented them using the SQL object: TIMESTAMP and recorded the timestamp using
TIMESTAMP(CURDATE(),CURTIME())
These store fine. Now I want to compute the difference between the two times, but it looks like PHP's TIMESTAMPDIFF() function takes in datetime objects instead of timestamp objects. There are a few ways I could move on from here, but I was wondering if there's a preferred way that SQL developers record and compute time differences. I need both the date and the time, so that I can get the difference accurate to the second.
This seems to be a 2 part question and is definitely duplicates of other questions on SO. A quick search produced a SO question that over 1000 people voted for DATETIME as the storage type (Should I use field 'datetime' or 'timestamp'?)
The main difference between DATETIME and TIMESTAMP in mysql is that TIMESTAMP will store that date at UTC and datetime will store your specific value. So if you don't need to translate between time zones, or have multiple time zones etc. Stick with DATETIME and the you don't have to convert or cast or anything.
As far as getting the difference between 2 datetimes or 2 timestamps I am certain their are SO questions on here I suggest searching a little more.

Date Time or Time Stamp? [duplicate]

This question already has answers here:
Should I use the datetime or timestamp data type in MySQL?
(40 answers)
Closed 9 years ago.
I am creating a table which has create_date and modify_date field in mysql, but I am struggling in decide which data type is the best choice for these 2 fields. Should i use date time for both fields, or should i use date time for create_date and time stamp for modify_date ?
Depends on your requirements. If you want to know the exact time these things happened then use a date/time (DATETIME in MySQL). Or, if you're happy with with just the date then choose date (DATE in MySQL)! If you don't know when maybe use DATETIME just to be safe (so you have the precision if you need it).
You're using MySQL so here is the documentation: http://dev.mysql.com/doc/refman/5.0/en/datetime.html
I'm assuming you're talking about a database table. If that is the case and you need to know date information choose a date time for both modify_date and create_date. If you don't need date information use a time stamp.
Sorry I'm from Ukraine and I use Google Translate. It all depends on how you are going to use them, if you take away from each other then TimeStamp, if just to show (for example in the news), then it is better Date Time. Generally I recommend TimeStamp

MySQL datetime into PHP

I have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.

MySQL: What's the best to use, Unix TimeStamp Or DATETIME [duplicate]

This question already has answers here:
Should I use the datetime or timestamp data type in MySQL?
(40 answers)
Closed 9 years ago.
Probably many coders want to ask this question. it is What's the adventages of each one of those MySQL time formats. and which one you will prefer to use it in your apps.
For me i use Unix timestamp because maybe i find it easy to convert & order records with it, and also because i never tried the DATETIME thing. but anyways i'm ready to change my mind if anyone tells me i'm wrong.
Thanks
Timestamp (both PHP ones and MySQL's ones) are stored using 32 bits (i.e. 4 bytes) integers ; which means they are limited to a date range that goes from 1970 to 2038.
DATETIME don't have that limitation -- but are stored using more bytes (8 bytes, if I'm not mistaken)
After, between storing timestamps as seen by PHP, or timestamps as seen by MySQL :
using PHP timestamps means manipulations are easier from PHP -- see Date/Time Functions
using MySQL's timestamps means manipulations are easier from MySQL -- see 11.6. Date and Time Functions
And, for more informations between MySQL's TIMESTAMP and DATETIME datatypes, see 10.3.1. The DATETIME, DATE, and TIMESTAMP Types
As others have said, timestamps can represent a smaller range of datetimes (from 1970 to 2038). However, timestamps measure the number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC), thereby making them independent of time zone, whereas DATETIME stores a date and time without a time zone. In other words, timestamps unambiguously reference a particular point in time, whereas the exact point in time a DATETIME refers to requires a time zone (which is not stored in a DATETIME field). To see why this can matter, consider what happens if we change our time zone.
Let's say we want to store the datetime 2010-03-27 12:00 UTC. If we store this and retrieve it using a timestamp or DATETIME, then there usually appears to be no difference. However, if the server now changes so that the local time zone is UTC+01, then we get two different results if we pull out the datetime.
If we'd set the field to a DATETIME, it would report the datetime as 2010-03-27 12:00, despite the change in time zone. If we'd set the field to a timestamp, the date would be reported as 2010-03-27 11:00. This isn't a problem with either datatype -- it's just a result of the fact that they store slightly different information.
That really depends. I'll give you 2 examples where one overcome the other:
Timestamp is better than DATETIME when you want to store users session in the database and the session creation time (in Timestamp format) is used for fast row retrieval (with index).
E.g. table may look like this:
[session_create_time AS Timestamp][IP_address AS 32bit Int][etc...]
Having an index on the first two columns can really speed up your queries. If you had a DATETIME value type for the session_create_time field, then it could be taken much more time. Take into account that session queries are executed each time a user request a page, so efficiency is crucial.
DATETIME is better than Timestamp when you want to store a user's date of birth or some historic events that require flexible time range.
Unless digitizing records prior to January 1, 1970, I like the UNIX epoch. Its just a matter of preference, whole unsigned numbers are simpler to deal with when using multiple languages.
Just keep in mind, the epoch starts at January 1, 1970. A lot of companies had been in business for decades, if not longer, prior to that.

Categories