Changing date format globally - php

I am using PHP and mysql and using either Date or DateTime to save dates in mysql database. On site I have been displaying dates the way they are saved in database.
But now I want to show dates EVERYWHERE on site using one format:
April 17 2013
or
April 17 2013 12:20:50
I know I can use date and strtotime functions to display dates in above format. However there are a lot of places where I have date displaying code. So I am looking to automate the process where my current code works and displays dates in above format.
Any idea of how mysql trigger or some php magic could be created that converts all dates run through SELECT query automatically without changing my sql or php code since I have a lot of places in my code and it would be overkill to change code at all places?
For Example:
Date Saved in DB: 2013-04-16 12:41:26
SELECT QUERY: SELECT * FROM myTable
PHP: echo $row->dated; displays 2013-04-16 12:41:26
I want that without changing my php code, dates should be shown in above mentioned format globally on whole site.
Any ideas please how it could be achieved ?

You can directly format in via query using DATE_FORMAT()
SELECT DATE_FORMAT(myDate, '%M %d %Y %h:%i') myDate
FROM TableName
SQLFiddle Demo
and echo in your PHP: $row->myDate
MySQL Trigger doesn't project values and It is only fired during CrUD operations.

I would like to suggest you an alternative approach which i love to use.
You should use the epoch time. An epoch time is basicly the number of second that has passed since 1 January 1970
One if the benefits i love is that it is very easy to calculate
differences in time since you are just dealing with number of
seconds and not a complicated format such as sec min hrs
Another benefit is that it is very easy to store since its a
integer so you can store it in a sql db and have your php code understand it without worrying about the format and things like that.
In php, if you use the time() function, it will return the epoch time.
And if you ever want to display it in a user friendly way. you can use the following code:
$epoch = time();
$dt = new DateTime("$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00
As you can see, the format of the date is very flexible and thus easy to use.
A nice example to find the date 1 week ago:
$epoch = time() - 604800; //604800 seconds = 7 days
$dt = new DateTime("$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00

Related

Displaying now() data in seperate day/month/year sections?

I am using a now() code to enter just a date into the database. The date appears as Year/Month/Day (yyyy/mm/dd).
In my PHP code I have been using:
$news_date=$row['news_date'];
to recall the date on my site, I was wondering, instead of the date all showing at once, is there a way to add a separate value for day, month and year? So I could recall 'day' separate and so forth? Obviously without changing the database to have 3 different inputs, there must be an easier way? I am fairly new to PHP and MySQL so if someone could help me out with an example that would be handy! Thanks.
PHP has a very powerful function called strtotime() that intuitively converts next to any datestamp into a UNIX-based timestamp, which you can then format any way you want.
$news_timestamp = strtotime($row['news_date']);
Now you can use PHP's date() function to output this timestamp in all sorts of ways.
print 'Today is day number '.date('d', $news_timestamp); // 20
print 'The month is '.date('F', $news_timestamp); // March
print 'Post timestamp: '.date('l, F d, Y # h:ia', $news_timestamp); // Thursday, March 20, 2014 # 03:46pm

PHP Datetime with MySQL datetime

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.

PHP / MySQL storing and searching dates

Like many people, I am totally confused by the many date functions in PHP and MySQL. What I need is a to be able to store a date in MySQL and be able to view it on the screen in a human readable format, search on it by month, year, or combination of both using a standard web form, or sort it on months or years.
Example search would be all the records for febuary for the past 5 years.
I have a javascript calendar that inputs the month in the form as 02-12-2011.
What is the best format to use for this. What should the field be in MySQL.
Thanks
Please make use of the DateTime object.
Store the dates in mysql as a DATE format.
When writing the data
$date = new DateTime($_POST['date']);
or
$date = DateTime::createFromFormat('d-m-Y', $_POST['date']);
$query = sprintf("INSERT INTO `data` SET `date` = '%s'", $date->format('Y-m-d'))
When reading the data out create a DateTime object.
$date = new DateTime($row['date']);
Then you can print it in whatever format you want, e.g. You javascript's format:
echo $date->format('d-m-Y');
See
http://www.php.net/manual/en/class.datetime.php
and for date formats:
http://www.php.net/manual/en/function.date.php
As far as searches go, you can use mysql Date functions on the fields.
For all records in February for the last 5 years.
SELECT * FROM `data` WHERE MONTH(`date`) = 2 AND YEAR(`date`) >= YEAR(NOW()) - 5
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
The column type in MySQL should be date.
it's a date, so store it as a DATE column. You can either use UNIX_TIMESTAMP() in your SQL query or strtotime in PHP, to convert this back to a value that can be passed in to the php date() function, to output whatever format date you'd like.

difference between two times in PHP

Hi All
im trying to build a simple form that the user use it to enter his leave request.
the form contains from time input field and to time input field,and these two filds will contains values in this syntax:
from time: 15:59 pm
to time: 16:59 pm
i have two questions:
1. what is the Datatype that i should use to store p.m and am in the record in mysql database, and not only the time?(i try to use Time,DateTime Date) but these datatypes only stores the time without p.m,a.m
2. what is the best way to calculate the diffrence between these two times?
Thank You
If you are comparing dates/times I find it easiest to work with a timestamp.
There are tons of date functions in PHP if it's just to output the date in the format you want have a look at date functions
The best way to store times in the database is in 24-hour time and use PHP's date function to format the time when you pull it to display it using AM or PM.
To compare two times, I suggest looking at thestrtotime function. This will return the time in UNIX fashion (seconds). You can then compare which time is greater or less than each other, or even perform basic mathematics operations on them (like determining the amount of seconds between each time and then dividing by 60 to determine minutes, etc).
Just store it as a timestamp, you can add pm/am automatically when you output:
print date('G:i a',1294239540); // prints 15:59 pm
and to get the difference in seconds just use strtotime and substract:
print (strtotime('16:59') - strtotime('15:59')); //prints 3600 (1 hour in seconds)
1) This doesn't make any sense - the database stores a representation of an exact instant in time, not an ambiguous 12 hour format with no am/pm. Regardless of how the db is storing it, you can just calculate the am or pm:
<?php
$am_pm = date('a', $timestamp);
?>
or even better, in mysql using your time field:
SELECT DATE_FORMAT(date_field, '%p')
2) For this you can use either php's date_diff, or in mysql:
SELECT DATEDIFF(date_one, date_two)
question 1
stored as time, which use ISO 8601 (hh:mm:ss)
question 2
use timediff, like
select timediff(cast('13:59:29' as time), cast('10:20:00' as time));
>> 03:39:29
To display the AM/PM
select time_format(cast('13:59:29' as time), '%r');
Storing am and pm when you're using 24 format is redundant. Anything between 11:59 and 00:00 is automatically pm. DateTime/timestamp should be more than sufficient to do what you're trying to accomplish. Then you can convert it using strftime back to 12-hr with am/pm.

Datetime value from database is three hours behind

I am using DATETIME as a column type and using NOW() to insert. When it prints out, it is three hours behind. What can I do so it works three hours ahead to EST time?
I am using php date to format the DATETIME on my page.
If the date stored in your database by using NOW() is incorrect, then you need to change your MySQL server settings to the correct timezone. If it's only incorrect once you print it, you need to modify your php script to use the correct timezone.
Edit:
Refer to W3schools' convenient php date overview for information on how to format the date using date().
Edit 2:
Either you get GoDaddy to change the setting (doubtful), or you add 3 hours when you insert into the table. Refer to the MySQL date add function to modify your date when you set it in the table. Something like date_add(now(), interval 3 hour) should work.
Your exact problem is described here.
Give gmdate() and gmmktime() a look. I find timestamp arithmetic much easier if you use GMT, especially if your code runs on multiple machines, or modifying MySQL server settings isn't an option, or you end up dealing with different timezones, day light savings, etc.
I would suggest inserting the date in UTC time zone. This will save you a lot of headache in the future (Daylight saving problems etc...)
"INSERT INTO abc_table (registrationtime) VALUES (UTC_TIMESTAMP())"
When I query my data I use the following PHP script
<? while($row = mysql_fetch_array($registration)){
$dt_obj = new DateTime($row['message_sent_timestamp']." UTC");
$dt_obj->setTimezone(new DateTimeZone('Europe/Istanbul'));
echo $formatted_date_long=date_format($dt_obj, 'Y-m-d H:i:s'); } ?>
You can replace the datetimezone value with one of the available php timezones here:

Categories