PHP MySql: how save timestamp UTC, like "Flickr"? - php

For default i'm using this snippet in my codes
setlocale(LC_TIME,'it_IT');
and I did save all my dates in mysql in a timestamp format.
In a view of make international one of my codes, i would like to save in MySQL a similar value
2013-07-12T07:59:27+0000
but of course with the +2 hours. So a Polish user will have a +3 and so on...
What's the best field for mysql to store that value? I need also to work with date, from PHP and/or from directly MySQL (for example)
SELECT id WHERE data BEETWEN [...]
Of course if I start with correct way, i don't need to change in future all my dbs, codes, etc...
Thank you very much!

For me is better store date time as UNIXTIME, it avoid the time difference between user from different locations.
You can use:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2013-07-12 07:59:27')
AND UNIX_TIMESTAMP('2013-07-13 07:59:27')
to get the Date Range

Related

Php/MySQL Auto date checking/comparing

Wanted to ask You how can I setup something on my php website, that would everyday automatically check and compare current date to all the database datetime entries and delete the rows of the dates that are in the past (for ex. if the current date is 2014-03-17, it would delete the rows that have datetime of 2014-03-16 ).
Because I basically have a TV-package website (not a real thing, just for a class), where you can order a package, you enter for how long and it adds that amount to current date, writes the order into database with the date written into a field named "expires". Would it make sense if I just wrote the checking function into the index, so when someone visits the site it would delete it? If so, how could I compare the two dates?
The DB example looks something like this: http://s29.postimg.org/7sbgj2hnr/dbtest.png
Although I highly recommend a scheduled task, you can do it in PHP by calling:
$sql = "DELETE FROM tableName WHERE `expires`<'".date('Y-m-d')."'";
Convert the date to a unix timestamp and compare it against the value of time() like you would any other integers.

MySQL custom Timestamp value

I'm having some troubles dealing with Timestamp data type in MySQL.
I'm saving simple records in my database using a simple DB structure, like:
ID int
Name varchar
Date timestamp
Text varchar
And then retrieve them with something like:
SELECT * FROM table WHERE Date BETWEEN '2013-01-01' AND '2013-06-30'
Everything works fine if I store records letting MySQL fill the Date field with the actual timestamp, for example: 2013-10-04 22:40:02 which means I don't add any value to the Date field in my INSERT query.
But I need to be able to add the date by my self since my application needs to store the date from where the application started, and not the date and time in which the query was sent to the database.
So what I do is I create the same date/time format my Date field uses which is 2013-10-04 22:40:02 and then do a simply insert:
INSERT INTO table (Name, Date, Text)
VALUES ('Peter', '2013-10-04 22:40:02', 'Hello...')
Now, doing it this way I'm unable to bring any result by date using a select query like this one:
SELECT * FROM table WHERE Date BETWEEN '2013-01-01' AND '2013-11-30'
Even if I try to sort results by Date using PHPMyAdmin interface, all the records that contain manually added dates disappear. If I sort them by ID, they re-appear. I checked and the dates and formats are correct. So I have no idea what the problem could be. I'm new at MySQL by the way.
Hope you can give me a hand. Thanks!
Well, I think I found the problem and it has nothing to do with PHP and MySQL, the problem is that I generate the date with JavaScript, and it's giving the wrong month.. :/
Thanks to everyone anyway!

Insert current date to MYSQL table, then echo back

It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
good luck! :)

Mysql how to set time data type to be only HH:MM in database

how can I set my mysql database field "time" data type to only be HH:MM in the database, in my script the user only enters HH:MM and the DB automatically adds the last :SS digits, the problem is when I pull that value to edit, it adds the last digits also, which is kind of annoying, I can get rid of it with PHP and truncating off the end, but I was hoping for a way to set it in the DB to remove those last 2 SS digits for good.
I don't believe you can configure your database to store the time without the SS.
MySQL's TIME DataType reference: http://dev.mysql.com/doc/refman/5.1/en/time.html
You'll have to set the formatting to HH:MM either in the mysql query or in php after you pull the data.
In PHP:
$date = date('H:i', strtotime($db_date_value));
http://us3.php.net/manual/en/function.date.php
In MySQL:
DATE_FORMAT(date_created, "%H:%i") as date_created
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
use TIME_FORMAT(time,format) function of mysql

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.

Categories