Converting mysql TIME from 24 HR to AM/PM format - php

I want to display the TIME field from my mysql table on my website, but rather than showing 21:00:00 etc I want to show 8:00 PM. I need a function/code to do this or even any pointers in the right direction. Will mark the first reply with some code as the correct reply.

Check this out: http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
I'd imagine you'd want date_format().
Example: DATE_FORMAT($date, "%r")

Show the date & time data in AM/PM format with the following example...
SELECT DATE_FORMAT(`t`.`date_field`,'%h:%i %p') AS `date_field` FROM `table_name` AS `t`
OR
SELECT DATE_FORMAT(`t`.`date_field`,'%r') AS `date_field` FROM `table_name` AS `t`
Both are working properly.

You can also select the column as a unix timestamp using MYSQL's UNIX_TIMESTAMP() function. Then format it in PHP. IMO this is more flexible...
select a, b, c, UNIX_TIMESTAMP(instime) as unixtime;
The in PHP use the date() function & format it any way you want.
<?php echo date('Y/m/d', $row->unixtime); ?>
The reason I like this method as opposed to formatting it in SQL is b/c, to me, the date's format is a display decision & (in my opinion) formatting the date in SQL feels wrong... why put display logic in your SQL?
Now - if you're not processing the data in PHP and are doing adhoc queries then DATE_FORMAT() is the way to go. But if you're gonna have the data show up on the web I'd go with UNIX_TIMESTAMP() and do the formatting in PHP...
I mean... lets say you want to change how the date & time are displayed on the page... wouldn't it feel "off" to have to modify your SQL for a display tweak?
my 2 cents

I had been trying to do the same and got this page returned from a Google search. I worked a solution for the time 21:00:00;
using DATE_FORMAT(<field>,'%l.%i%p') which returned 9.00PM
putting a LOWER() function around it to return 9.00pm
So the full code is; DATE_FORMAT(<field>,'%l.%i%p')
Worked OK for me ...

Use DATE_FORMAT()
DATE_FORMAT(<Fieled>,'%h:%i:%s %p')
or
DATE_FORMAT(<Fieled>,'%r')

Related

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! :)

In MySQL, how to convert this string to a date?

I am creating a mysql db with a php frontend. The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened.
I understand that this might be a UNIX timestamp? Not sure.
I want to be show this field in the tables in my PHP webpage as a readable date and time -
ie something like 01-Mar-2012 07:31:36 or similar
Should I try and convert it with SQL command or let PHP format it? And, what is the code to do so?
BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened.
Thanks in advance for your help - Ive learnt a lot here already
J
You can convert it to a datetime directly in your SQL query. Example:
select cast(20120301073136 as datetime)
You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss
select * from yourTable
order by yourDateTimeField
You should make use of the MYSQL DATE functions. Check the docs before asking simple questions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.
Also you can sort the dates directly in your query using ORDER BY.

date different with php comparing returned date from DB and current date

let say i have a date Jun 9 2008 12:00AM and want to calculate how many days from NOW.
can i do it using php ?
Note: The possible date can also be returned as 09/06/2008.
Try to use DATEDIFF frm http://msdn.microsoft.com/en-us/library/ms189794.aspx but no luck..
You have tried the Microsoft SQL Server version of DATEDIFF, but your question is tagged as MySQL.
Try this one:
SELECT DATEDIFF(CURDATE(), yourDateColumn) FROM yourTable;
UPDATE (now that we know that it's actually MSSQL):
You need to clarify your question. What do you mean with "I have a date"? Is the date in the database? If yes, show the way you tried the DATEDIFF function. If it's a valid date in the database it doesn't matter how it is formatted and the following should definitely work:
SELECT DATEDIFF(d, yourDateColumn, GETDATE()) FROM yourTable;
Is the column type maybe not date but varchar? Then you can convert it like this:
SELECT CONVERT(datetime, yourDateColumnOrYourStringOrWhatever , format) ...
Here you can see which formats you can use.
Again, post more info or we can't help you. And I'm not going to guess around more.
You should use mysql DATEDIFF function.
if you want to do it in php, so:
round((strtotime('now')-strtotime('Jun 9 2008 12:00AM'))/3600/24)
but DATEDIFF is much better

PHP/MySQL - Display DateTime as Date

I'm a little knew to SQL & PHP and have been given the task of displaying some information from the database. I know how to query my database and display the info into tables on screen using PHP and so forth; however this time I've been given a slightly different challenge.
I have information stored in the DateTime format in the SQL database and whilst retrieving it I need to strip the time and display only the date. I've had a read through many of the date/time functions for SQL but for some reason this seems to be going almost straight over my head. I've had a browse of a few sites including the two links below, but I'm having a hard time understanding how to do such things within PHP etc. If someone could steer me in the right direction that would be excellent!
2 somewhat related threads I've browsed:
http://www.gfxvoid.com/forums/showthread.php?28576-PHP-Time-Date-Display
http://blogs.x2line.com/al/archive/2006/02/17/1458.aspx
Logically, am I supposed to query the DateTime and then use PHP to reformat it the way I wish to display it? Or am I supposed to format the datetime using an SQL query?
Thanks very much!
Just use the DATE function around the date time.
SQL Column: created_at
2012-05-09 13:46:25
SELECT DATE_FORMAT(DATE(created_at), '%D %M %Y') FROM Table
Returns:
9th May 2012
EDIT as per comment:
To use it in PHP, you can do something like the following:
Query: (Notice the AS clean_date)
SELECT DATE_FORMAT(DATE(created_at), '%D %M %Y') AS clean_date FROM Table
then in in php:
<?php
echo "<tr><td>{$row['clean_date']}</td>";
?>
Can you check this in PHP when Display the date from Mysql
date('Y/m/d', strtotime($datetodisplay));
Sometime when you fetch the date from mysql, we have change that to time by using strtotime() funciton

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