im storing the dates that entries were posted on in the db using a standard unix timestamp.
is it possible, using only a mysql query (no php logic), to select entries that were posted in a certain year?
id like to avoid retrieving ALL entries and then using php to filter on year value. i could store the year in a separate field of course, just curious about this
This should be what you're after:
SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year FROM table_name WHERE my_unix_timestamp_column BETWEEN UNIX_TIMESTAMP('2004-01-01 00:00:00') AND UNIX_TIMESTAMP('2004-12-31 23:59:59');
You only want MySQL to do the hard work of extracting the year once:
SELECT your, columns
FROM posts
WHERE postdate BETWEEN UNIX_TIMESTAMP('20080101') AND (UNIX_TIMESTAMP('20090101')-1)
Obviously, this adapts easily to extract posts within a certain month or day or decade etc.
maybe use the FROM_UNIXTIME() function
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime
A better way to do that is to use a little bit of PHP to create the unix timestamp you want. If it is this year try
$timestamp = strtotime("January, 1, 2009");
$db->query("Select * from table where time < $timestamp");
This is just an example, but you will be able to quickly narrow your results and only do very minimal php logic.
Depends of your mysql version. 5.1 has this neat function FROM_UNIXTIME(unix_timestamp,format)
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
-> '%Y %D %M %h:%i:%s %x');
-> '2007 30th November 10:30:59 2007'
Related
I am trying to convert long date format string (e.g. 1st-June-1999 or 20th-March-2001) to date YYYY-MM-DD using MySql 5.7.
Reading docs tried to use STR_TO_DATE:
select STR_TO_DATE(dob,'%d-%M-YYYY') from table
However, this returns null due to the day suffix (e.g. th).
I could use update query with REPLACE() to remove the suffix and then STR_TO_DATE, but is there a better solution?
You have two problems. First, you need %D (capital not lowercase) since you have the suffix after the day of the month.
Next, the year should simply be %Y.
So, the select statement would be
select STR_TO_DATE(dob,'%D-%M-%Y') from table;
w3schools has a good reference for the abbreviations: https://www.w3schools.com/sql/func_mysql_str_to_date.asp
%D does what you want:
str_to_date(dob, '%D-%M-%Y')
A couple of questions.
In SQL Developer I could type alter session set nls_date_format='DD-MON-YY HH:24:MI:SS'; to include the time and all queries on that tab would then include this format. I could then type alter session set nls_date_format='DD-MON-YY'; to remove the time. Any easy equivalent in MySQL that could flip my date formats like this?
If it's not that simple, let me ask this: Can the format be changed on a single query line. So if i have this
select name, start_date from Users;
If this normally shows the date and time, how can i alter it to only have the results show just the date?
Any easy equivalent in MySQL that could flip my date formats like this?
Yes, there is.
What you're looking for is the DATE_FORMAT() function.
Example:
select DATE_FORMAT(start_date,'%d-%m-%Y') from Users
Adjust the specifiers as needed.
Common specifiers:
%d day of month
%m month
%Y year
%H hour (00..23)
%h hour (01..12)
%p AM or PM
%i minutes
%s seconds
For other specifiers, see DATE_FORMAT().
start_date is presumably a datetime column. You can truncate the time by converting it to a date:
SELECT name, DATE(start_date)
FROM users
I have a column that stores dates as text, I need to select all the entries with date less than the date of today.
If I use this:
SELECT *
FROM mytab
WHERE expire < CURRENT_DATE( )
ORDER BY expire DESC
It doesn't select the correct entries but only the ones with da_expire empty.
How can I fix it?
In the first place, why are you storing it as string?
You need to convert it to date using MySQL's builtin function so you can be able to compare it with today's date.
WHERE STR_TO_DATE(expire, '%Y/%m/%d %H:%i') < CURDATE()
This will be a little slower since it will not use any index if you have one defined on the column.
MySQL Docs: STR_TO_DATE()
Use STR_TO_DATE(expire, '%m/%d/%Y') instead of expire in the query. I have assumed you are storing the date in month day year format. You will need to adjust the format as per the string format. However, for performance reasons convert the type of expire during load/insert process .
How do I extract the month and date from a mySQL date and compare it to another date?
I found this MONTH() but it only gets the month. I looking for month and year.
in Mysql Doku:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract
SELECT EXTRACT( YEAR_MONTH FROM `date` )
FROM `Table` WHERE Condition = 'Condition';
While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss.
DATE_FORMAT works really well and is flexible to handle many different patterns.
DATE_FORMAT(date,'%Y%m')
To put it in a query:
SELECT DATE_FORMAT(test_date,'%Y%m') AS date FROM test_table;
If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use
SELECT YEAR(date) AS 'year', MONTH(date) AS 'month'
FROM Table Where Condition = 'Condition';
SELECT * FROM Table_name Where Month(date)='10' && YEAR(date)='2016';
You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?
There should also be a YEAR().
As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)
Or you could use multiple comparisons (i.e. years first, then months).
Is there a MySQL function which can be used to convert a Unix timestamp into a human readable date? I have one field where I save Unix times and now I want to add another field for human readable dates.
Use FROM_UNIXTIME():
SELECT
FROM_UNIXTIME(timestamp)
FROM
your_table;
See also: MySQL documentation on FROM_UNIXTIME().
What's missing from the other answers (as of this writing) and not directly obvious is that from_unixtime can take a second parameter to specify the format like so:
SELECT
from_unixtime(timestamp, '%Y %D %M %H:%i:%s')
FROM
your_table
I think what you're looking for is FROM_UNIXTIME()
Need a unix timestamp in a specific timezone?
Here's a one liner if you have quick access to the mysql cli:
mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';
+---------------------+
| local time |
+---------------------+
| 2016-06-27 23:37:31 |
+---------------------+
Replace 'MST' with your desired timezone. I live in Arizona 🌵 thus the conversion from UTC to MST.
Why bother saving the field as readable? Just us AS
SELECT theTimeStamp, FROM_UNIXTIME(theTimeStamp) AS readableDate
FROM theTable
WHERE theTable.theField = theValue;
EDIT: Sorry, we store everything in milliseconds not seconds. Fixed it.
You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.
Easy and simple way:
select from_unixtime(column_name, '%Y-%m-%d') from table_name
Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.
I have an automatically updated last_modified field, defined as:
`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC
SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,##session.time_zone,'+00:00') as UTC FROM `table_name`
In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.
Run this twice, first without setting the time_zone.
If you would like to convert time AND display the data in a specific format you can use this string.
date_format(convert_tz(from_unixtime(TIMESTAMP), 'UTC', 'DESIRED TZ'), '%m/%d/%y')
where you add convert_tz to a date_format string. the %m/%d/%y being month/day/year.
you can find all the specific formats here https://www.w3schools.com/sql/func_mysql_date_format.asp