I need your help with datetime coversion. Inside my database I have date of comments entered like this:
Datetime: 2012-05-08 14:44:53
How can I make it display something close to this
May 15, 2012 2:44PM
Thanks for your time and patience.
DATE_FORMAT() is the answer to your question. It has several formats of date on this link
SELECT DATE_FORMAT(NOW(), '%M %d, %Y %h:%i %p') as FormattedDate;
View The Output Here [SQLFiddle]
%M Month name (January..December)
%d Day of the month, numeric (00..31)
%Y Year, numeric, four digits
%h Hour (01..12)
%i Minutes, numeric (00..59)
%p AM or PM
You need to use strtotime() to convert to a Unix timestamp. You can then use date() to display the exact format you need. Something like this:
$unix = strtotime($datetime);
echo date(F j Y g:iA, $unix);
You should use MySQL DATE_FORMAT() function.
Reference:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
Example query:
SELECT DATE_FORMAT(`date`, '%a %d, %Y %l:%s%p') AS `myDate`;
Related
I am trying to select data from a table mysql but I need to format a varchar date column in a military format, but cannot get my desire output my query is below.
"SELECT STR_TO_DATE(`hour`, '%Y-%m-%d %k:%i') AS `time` FROM `dataTable`"
When I tried to echo the time below format appear.
2017-09-21 00:00:00
My desire output is below which is in 24 hour format and removing the seconds, any suggestions would be great.
2017-09-21 18:00
Use the Date_format function of mysql.
"SELECT DATE_FORMAT(`hour`, '%Y-%m-%d %H:%i') AS `time` FROM `dataTable`"
Explanation:
The STR_TO_DATE function always return the date in the format of 2008-09-15 22:23:00
SELECT STR_TO_DATE('Monday 15th September 2008 22:23:00', '%W %D %M %Y %H:%i:%s');
+----------------------------------------------------------------------------+
| STR_TO_DATE('Monday 15th September 2008 22:23:00', '%W %D %M %Y %H:%i:%s') |
+----------------------------------------------------------------------------+
| 2008-09-15 22:23:00 |
+----------------------------------------------------------------------------+
1 row in set (0.00 sec)
Check the above example: the second parameter in STR_TO_DATE function is the format of the parameter 1 to tell the function that in which format parameter 1 is passed in the function.
Reference taken from this link.
I have two STRING fields in my table which make up the date and time. I want to concat those fields, convert them into a date so I can get the values between a chosen time. I think I'm running into a problem with str_to_date format inside my query. Here's what I have in the table
theDate theTime
Mon, Jan 20 7:00 pm
Mon, Jan 20 9:00 pm
Tue, Jan 21 5:00 pm
The PHP:
date_default_timezone_set('EST');
//trying to set up the same format as the concatenated fields will be
$now = date('D, M j g:i a');
include('..//db_connect.php');
try {
$stmt = $conn->query("SELECT * FROM table1 WHERE STR_TO_DATE(CONCAT(theDate, ' ', theTime), '%a, %b %e %l:%i %p')
BETWEEN (STR_TO_DATE('$now', '%a, %b %e %l:%i %p') - INTERVAL 4 HOUR AND STR_TO_DATE('$now', '%a, %b %e %l:%i %p') - INTERVAL 10 HOUR)");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
} catch (Exception $e) {
echo $stmt."<br>".$e->getMessage();
}
What I get is syntax error near 'HOURS AND STR_TO_DATE('Wed, Jan 21 7:07', '%a, %b %e %l %i') - INTERVAL 10 HOURS' at line 2. What's wrong with the query? Also, is there a way to print out the query itself, to see the concatenated values, to see the formatted values?
One thing is wrong is HOURS. Must be HOUR
This is your query:
SELECT *
FROM table1
WHERE STR_TO_DATE(CONCAT(theDate, ' ', theTime), '%a, %b %e %l %i %p')
BETWEEN (STR_TO_DATE('$now', '%a, %b %e %l %i %p') - INTERVAL 4 HOURS AND
STR_TO_DATE('$now', '%a, %b %e %l %i %p') - INTERVAL 10 HOURS)
This doesn't quite look like MySQL syntax. There are several small problems -- the hours and the extra parentheses around the BETWEEN, the BETWEEN valus in the wrong order. Perhaps this does what you want?
SELECT *
FROM table1
WHERE STR_TO_DATE(CONCAT(theDate, ' ', theTime), '%a, %b %e %l %i %p')
BETWEEN date_sub(now(), interval 10 hours) AND
date_sub(now(), interval 4 hours);
You should use native types for dates and times in the database, rather than storing them as strings. If they are strings, don't give them names like "date" and "time" that suggests that they are something they are not.
I think you will need to pass in the year somewhere... also your are missing the colon : on the STR_TO_DATE. It's HOUR in singular
Try like this:
// Assuming $now is in the format '2014 Wed, Jan 21 7:07'
SELECT STR_TO_DATE('$now', '%Y %a, %b %e %l:%i') - INTERVAL 4 HOUR;
As per the second part of the question, I think you could do a separated query like this:
SELECT STR_TO_DATE('$now', '%Y %a, %b %e %l:%i') - INTERVAL 4 HOUR, STR_TO_DATE('$now', '%a, %b %e %l:%i %p') - INTERVAL 10 HOUR;
And then show the results, to see what are the actual values being looked up.
I guess your error is that you are using HOURS instead of HOUR, but I suggest a better solution to use date_sub() and mysql now() methods into something like:
SELECT * FROM table1 WHERE myDate BETWEEN date_sub(now(), INTERVAL 4 HOUR) AND date_sub(now(), INTERVAL 10 HOUR);
An other sugestion is to save datetime fields as datetime and not as string less work after.
This is the query that I'm trying to run in my SQL phpMyAdmin to retrieve 2 rows of data:
SELECT * FROM table WHERE STR_TO_DATE(theDate, '%a, %b %e') = DATE_FORMAT(curdate(), '%a, %b %e')
I get no errors, also no results. The format of the string in theDate column is like this for today's date:
Tue, Jan 20
What am I doing wrong in the conversions comparison?
Your date format is missing a year, which complicates date comparisons. The best solution is probably to convert the current date to a string:
WHERE thedate = DATE_FORMAT(curdate(), '%a, %b %c')
You should use native date/time formats for these columns, not strings.
STR_TO_DATE() creates a date from a string, while CURDATE() returns a date directly.
This should work:
WHERE STR_TO_DATE(theDate, '%a, %b %c') = curdate()
STR_TO_DATE(theDate, '%a, %b %c') is convert date row string date into Y-m-d format
and you are trying to compare as in query
`%Y-%m-%d` = '%a, %b %c'
try this query if you want to compare date in other format
If theDatedate store in format Tue, Jan 20
SELECT * FROM table WHERE
theDate =
DATE_FORMAT(curdate(), '%a, %b %c')
Problem
I have the last data entry in date_time for 9th of april 2013 whereas when I try to fetch in descending order from the database it is giving me 8th April 2013. Please see the image and Code below. Any help will be appriciated.
Database
Code
SELECT *
FROM data_feeds
WHERE username = 'davidjhume#gmail.com'
AND gadget_data_type = 'Weighin'
ORDER BY STR_TO_DATE( date_time, '%D, %j %M %Y %H:%i:%s' ) DESC
LIMIT 1
Format string is broken, try:
'%a, %e %b %Y %H:%i:%s'
Your format for str_to_date() is wrong
You say
%D, %j %M %Y %H:%i:%s
So according to you the second value is %j. But according to Mysql docs %j is 'day of year'. https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
edit: you have multiple errors in the format. Try: %a, %e %b %Y %H:%i:%s
I want to get formated date in php from mysql database Like 21st March 2013 11:21AM
You can use MySQL's built-in function called DATE_FORMAT()
SELECT DATE_FORMAT(NOW(), '%D %M %Y %h:%i%p')
SQLFiddle Demo
DATE_FORMAT()
OUTPUT
╔═════════════════════════╗
║ FORMATTED_DATE ║
╠═════════════════════════╣
║ 22nd March 2013 06:07AM ║
╚═════════════════════════╝
You can use DATE_FORMAT MySQL function.
Example
DATE_FORMAT(NOW(),'DATEFORMATE') // DATEFORMATE can be %b %d %Y %h:%i %p
OR
STR_TO_DATE('$date', 'DATEFORMATE')
HOW TO USE IN QUERY
SELECT STR_TO_DATE('YOUR DATE FIELD','DATEFORMAT') FROM table;
SELECT DATE_FORMAT(NOW(),'DATEFORMAT') FROM table;
DATEFORMATE Options
Why not use MySQL's DATE_FORMAT?
For your example, add this to your MySQL query:
DATE_FORMAT(my_date, '%e %M %Y %h:%i %p')
Use DATE_FORMAT()
SELECT * FROM table DATA_FORMAT(NOW(), '%D %M %Y %h:%i%p')
Tutorial on DATE_FORMAT
What format is your database column in? If it's a UNIX timestamp, just feed it into date. If it's a date column (formatted as 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'), feed that into strtotime, then into date.
So, assuming it's a date column, you'd want to do something like this:
$column_value = "2013-03-01 00:00:00"; // Get this from your database however you like
$formatted_date = date("jS F Y H:i A", strtotime($column_value));
The documentation on how to use date for formatting is in the PHP documentation.
Try this :
$date = date from databse // some thing like 2013-03-22 11:38:00
$dt = new DateTime($date);
echo $dt->format('jS F Y g:ia');
Output : 22nd March 2013 11:38am
Ref : http://www.php.net/manual/en/datetime.format.php