Storing timestamp in MySQL - php

I'm grabbing data from a webpage that returns a timestamp in the following form (which is a string):
2013-11-09T15:14:48.957604
How can I interpret this in PHP, and what is the best way to store this in a MySQL database?

The best way to store it is to use the MySQL DATETIME data type. It is specifically meant to handle date/time values, and it works beyond the year 2037, which is the approximate limit using unix timestamps. MySQL and PHP both handle these values with ease using built in functions/libraries (for PHP, see the DateTime class as mentioned by another commenter).
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
http://php.net/manual/en/class.datetime.php

I just want to expand on the information given here.
This will convert the string into a DateTime object.
$dtObject = new DateTime("2013-11-09T15:14:48.957604");
But, in order to store the timestamp in the database there are several requirements.
Needs to be in Y-m-d H:i:s format.
MYSQL column type must be datetime/timestamp
Needs to be a string.
Now in order to get this timestamp into a MYSQL friendly format we need to use the format function.
$timestamp = $dtObject->format('Y-m-d H:i:s');
You can now INSERT this into the database. You can also output the same way following these date formats.

Related

What's the best way to store date and time in a MySQL database for later display with PHP?

I want to store the date and time that a user performs an action on my website into a MySQL database. I'd like to be able to do the following with ease:
Store the date and time as one field in the database
Use a built in PHP or MySQL function to generate the date-time of the action
Store the date-time based on my server's time, and not worry about user timezones.
Order By the date-time field when I query MySQL
Later, display the date-time in many different formats using built in PHP methods
Here are my questions:
What data type should I use in MySQL ( eg. timestamp, datetime ... )?
What method should I use to generate the date-time ( eg. MySQL's now(), PHP's date() ... )?
What PHP method should I later use to format the date-time in various pretty ways ( eg. 23/4/2012, 5pm on Monday, July 2012 ... )?
I would store it as a datetime, not a timestamp.
I normally use the PHP date function and that way if you ever want to store the time relative to the user's timezone you can simply change the timezone based off the user's settings.
When you pull it out of the database, use strtotime() to convert it, then you can use all the date() features to display it however you want. Example:
echo date('F j, Y',strtotime($db_datetime)); //Displays as 'March 5, 2012'
I've struggled with this question for years, and I'm beginning to think that the best way might be to store the time as an integer that represents Unix time (number of seconds from Jan 1, 1970). I've done this and it works fine.
Personally I've never used datetime, and I can't think of a situation when I ever would use this. It just carries too many problems with it.
Timestamp is a lot better, but in MySQL it can't store a date later than 2032.
I would love to hear some serious discussion on this topic, but Stack Overflow might not be the best place for this.
If you set the mysql data type to a non-nullable timestamp, then save rows with a null value for that column, mysql will automatically update the timestamp for you.
As for reading it back out again, you can just use php's strtotime and the date object to get it into the format you need.
You should use the datetime datatype for your requirement.
It will store both the date and time from your input field based on your query.
For retrieving the datetime you can use the mysql's date_format() function or PHP's date() function.
The datetime will always be stored according to the server's time and not on the clients time.

How would I do the mysql timestamps in php?

Ok so I have a mysql database and I need an updated_at field and a created_at field like ruby on rails has by default. I was thinking of using a timestamp for the updated field and a datetime for a created at field. I was reading this article to help me choose but i still dont know if there is a standard that is followed that will either do this automatically with automatically or with little extra code...any ideas on this
The best practice would be to use UNIX Timestamps on both.
To have UNIX timestamp in PHP, use the
time();
function, and to have it in MySQL use the
UNIX_TIMESTAMP();
function. PHP can simply convert UNIX timestamps to any formatted date string using
Date();
function. And you can also make calculations with that.
Well the code from php will only provide you with your time as your computer see's it. Where mysql it has the CURRENT_TIMESTAMP.
You could do it entirely in your database management system. For example, MySQL has functions to use the current date or time: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Example: insert into a (CURRENT_TIMESTAMP);
You are on track with using TIMESTAMP for your updated field which provides the functionality you are looking for. To keep your date format consistent, I would then use DATETIME for your created field and use now() on insert.
I prefer UNIX timestamps, but then you have to code for the updated_at field.

date problem in php

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.

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.

What is the preferred format to store date/times in a SQL Server database when PHP is your primary language?

I am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information?
MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSSQL functions to translate datetime values to PHP's preferred format--UNIX timestamp. This makes it a bit more painful to use with PHP. UNIX timestamp is attractive because that's what PHP likes, but it's certainly not as readable and there aren't a bunch of nice built-in MSSQL functions for working with the data.
Would you store this information as datetime data type, as UNIX timestamps (as int, bigint, or varchar datatype), as both formats side by side, or as something else entirely?
I would store the dates in the MS-SQL format to assist in using the date manipulation functions in T-SQL to their fullest. It's easier to write and read
SELECT * FROM Foo
WHERE DateDiff(d,field1,now()) < 1
Than to try and perform the equivalent operation by manipulating integers
To convert a MsSQL date into a unix timestamp use dateDiff:
SELECT DATEDIFF(s,'1970-01-01 00:00:00',fieldName) as fieldNameTS
FROM TableName
WHERE fieldName between '10/1/2008' and '10/31/2008'
To Convert an Unix Timestamp into a MsSQL Date, you can either do it in PHP:
$msSQLDate = date("Y-m-d H:i:s", $unixDate );
or in MsSQL
INSERT INTO TableName (
fieldName
) VALUES (
DATEADD(s,'1970-01-01 00:00:00', ? )
)
Where parameter one is int($unixDate)
I'd recommend the same as i do for all dates in any db engine, the db native type. (DATETIME)
Just use "YYYY-MM-DD HH:MM:SS" for inserting in php: date('Y-m-d H:i:s', $myTimeStampInSeconds);
-edit in response to comments below here -
for selected columns you can use $timestamp = strtotime( $yourColumnValue );
i recommend storing in the databas native format because you can then use SQL to compare records using SQL date/time functions like DATEADD() etc.
Hello and good day for everyone
Yes , might be thats the best way , store dates in db, they will take db format and you can format when you need as you wich
But there is another one solution in the ISO-developed international date format, i mean ISO 8601.
The international format defined by ISO (ISO 8601) tries to address all date problems by defining a numerical date system as follows: YYYY-MM-DD where
YYYY is the year [all the digits, i.e. 2100]
MM is the month [01 (January) to 12 (December)]
DD is the day [01 to 31] depending on moths :P
Using numerical dates does have also some pitfalls with regard to readability and usability it is not perfect.But ISO date format is, however, the best choice for a date representation that is universally (and accurately) understandable.
Note that this format can also be used to represent precise date and time, with timezone information
Here is a detailed information about ISO 8601:2000
http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/date_and_time_format.htm
With no more....
Bye bye

Categories