Extract only the month in a query CodeIgniter - mysql

I want to make a query where I get people birthday's in a current month, I have problems with MONTH() it does not work for me, the date format in the database is: 04/18/1990, and I want to compare if the month current date('m') is equal to the month of the database.
Any suggestions?

you can try this one
SELECT * FROM table_name where extract(month from BirthDate) = date("m");
where date("m") return current month and BirthDate is column name in which you have stored birthdate.

Try this
"select month(str_to_date(birthdate), '%Y/%m/%d')
from users
where month(str_to_date(birthdate), '%Y/%m/%d') = '$month'"
Here, i m assuming your delimeter is '/', Please set your delimeter according to your string date i.e 2013/05/04 or 2013,05,04 or 2013-05-04

could be you have some convertion issue try using
select month(str_to_date(my_col, '%m/%d/%Y'))
from my_table
where month(str_to_date(my_col, '%m/%d/%Y')) = month(now())

Related

Mysql Select with Dates and maybe Case when

im having a problem where i cant think of a solution, maybe im having a bad table-structure or i just dont know enough about mysql select commands to think of a good solution. Maybe you can help me out:
So i got a table that has a Column with the Date-format (yyyy-mm-dd) i wanted to select all upcoming dates so i did:
SELECT * WHERE date >= now.
This worked kinda well but i also got "dates" where only the year is entered (2014-00-00) i also wanted to select these but "now" is already bigger so i made another column with the year only and if the month, date or both arent known i will use 0000-00-00 and the Column "year" now i could select like this:
SELECT * WHERE date >= now AND year >=now(year)
Now all entrys with 0000-00-00 wont be selected. If i use OR the entrys from last year will be shown.
So thats my problem, is there any way i can change my table so i can have entries with only the year or only year and month and of course all together? I already considered get rid of the date-format and use simple INT with seperated columns for year, month and date. But i think i will have the same problem.
Sometimes i just want to do a capsuled select like
SELECT *
WHERE (date >= now AND year >= now(year))
OR date == "0000-00-00" (i know that this doesnt work)
If I understood your problem correctly, you could use this request:
WHERE (date >= now OR year > now(year))
There is probably a simpler way though, that would preserve your design, like initializing at January 1st (01-01) instead of 00-00
I think you can use this code:
$_SESSION['month'] = //set here your selected month
$_SESSION['year'] = //set here your selected year
SELECT * FROM table WHERE DATEPART(m,date) >= '".$_SESSION['month']."' AND DATEPART(yyyy,year) >= '".$_SESSION['year']."' AND date <> '0000-00-00'
Change your table structure format. Actually just allow for that field to have null value when not entered. By default it will be null then. You shouldn't be storing 0000-00-00 as a value for Date type field. I would rather leave it as null , or as suggested in some of previous answers, initialize it with some other date. It would be much easier to manipulate with database then.
the problem is that half of you write is not MySQL and your database schema is terrible...
You have the following problems:
column data date does not have the date data type.
To fix it, you need to add a cast to the select statement eg. cast(datecolumn as date)
select * from table where cast(datecolumn as date) >= '2014-01-10';
the way to use now date is using the now function.
select now(), date(now());
result> 2014-01-10 11:11:36, 2014-01-10
select * from table where cast(datecolumn as date) >= date(now());
Because your datecolumn is not a date (2014-00-00 is not a valid date), you need to use string manipulation to extract the year.
select substring('2014-01-01', 1,4)
result> 2014
select * from table where substring(datecolumn, 1,4) = year(now());
The comparassion operator is = and not ==
the select statement syntax looks like this (pay attention because you are missing the table in your statement)
select * from [Table] where [column] = condition ...
You probably need or instead of ands, therefore your query should look like this:
select * from FooTable where
cast(datecolumn as date) >= date(now())
or substring(datecolumn, 1,4) >= year(now())
or datecolumn = '0000-00-00'
You should use something like phpmyAdmin or mySQL workbench to test your sql queries before try to use them on php, java or whatever is your programing language.

Fetch month and day value from date attribute of table in mysql

I have created a table as below.
actor(id, first_name, last_name, dob);
Where dob is in Y-m-d format. So I would like to fetch actors, who they have b'days for perticluar month or perticcular day. Please help me to get the solution.
Use this query for date
select * from actor where DAY(dob) = 12;
And for month
select * from actor where MONTH(dob) = 5;
You can combine both of them as well using AND operator.
Have a look at this. You will find more date and time functions that you can use
Try day and month functions
select * from actor
where day(dob)=x and month(dob)=y
See more datetime functions here http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

How to select only date from a DATETIME field in MySQL?

I have a table in the MySQL database that is set up with DATETIME. I need to SELECT in this table only by DATE and excluding the time.
How do I SELECT in this table by only date and bypassing the time, even if that specific column is set to DATETIME?
Example
Now it is: 2012-01-23 09:24:41
I need to do a SELECT only for this: 2012-01-23
SELECT DATE(ColumnName) FROM tablename;
More on MySQL DATE() function.
you can use date_format
select DATE_FORMAT(date,'%y-%m-%d') from tablename
for time zone
sql2 = "SELECT DATE_FORMAT(CONVERT_TZ(CURDATE(),'US/Central','Asia/Karachi'),'%Y-%m-%d');"
Try to use
for today:
SELECT * FROM `tbl_name` where DATE(column_name) = CURDATE()
for selected date:
SELECT * FROM `tbl_name` where DATE(column_name) = DATE('2016-01-14')
You can use select DATE(time) from appointment_details for date only
or
You can use select TIME(time) from appointment_details for time only
In MYSQL we have function called DATE_FORMAT(date,format).
In your case your select statement will become like this:-
SELECT DATE_FORMAT(dateTimeFieldName,"%a%m%Y") as dateFieldName FROM table_name
For more information about Mysql DATE and TIME functions click here.
Please try this answer.
SELECT * FROM `Yourtable` WHERE date(`dateField`) = '2018-09-25'
Simply You can do
SELECT DATE(date_field) AS date_field FROM table_name
I tried doing a SELECT DATE(ColumnName), however this does not work for TIMESTAMP columns† because they are stored in UTC and the UTC date is used instead of converting to the local date. I needed to select rows that were on a specific date in my time zone, so combining my answer to this other question with Balaswamy Vaddeman's answer to this question, this is what I did:
If you are storing dates as DATETIME
Just do SELECT DATE(ColumnName)
If you are storing dates as TIMESTAMP
Load the time zone data into MySQL if you haven't done so already. For Windows servers see the previous link. For Linux, FreeBSD, Solaris, and OS X servers you would do:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
Then format your query like this:
SELECT DATE(CONVERT_TZ(`ColumnName`, 'UTC', 'America/New_York'))
You can also put this in the WHERE part of the query like this (but note that indexes on that column will not work):
SELECT * FROM tableName
WHERE DATE(CONVERT_TZ(`ColumnName`, 'UTC', 'America/New_York')) >= '2015-02-04'
(Obviously substitute America/New_York for your local time zone.)
† The only exception to this is if your local time zone is GMT and you don't do daylight savings because your local time is the same as UTC.
Try
SELECT * FROM Profiles WHERE date(DateReg)=$date where $date is in yyyy-mm-dd
Alternatively
SELECT * FROM Profiles WHERE left(DateReg,10)=$date
Cheers
Yo can try this:
SELECT CURDATE();
If you check the following:
SELECT NOW(); SELECT DATE(NOW()); SELECT DATE_FORMAT(NOW(),'%Y-%m-%d');
You can see that it takes a long time.
Select * from table_name where date(datetime)
Use DATE_FORMAT
select DATE_FORMAT(date,'%d') from tablename =>Date only
example:
select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;
you can use date_format
select DATE_FORMAT(date,'%y-%m-%d') from tablename
for time zone
sql2 = "SELECT DATE_FORMAT(CONVERT_TZ(CURDATE(),'US/Central','Asia/Karachi'),'%Y-%m-%d');"
You can use select DATE(time) from appointment_details for date only
or
You can use select TIME(time) from appointment_details for time only
if time column is on timestamp , you will get date value from that timestamp using this query
SELECT DATE(FROM_UNIXTIME(time)) from table
SELECT DATE_FORMAT(NOW() - INTERVAL FLOOR(RAND() * 14) DAY,'%Y-%m-%d');
This one can be used to get date in 'yyyy-mm-dd' format.
if time column is on timestamp , you will get date value from that timestamp using this query
SELECT DATE(FROM_UNIXTIME(time)) from table
In the interest of actually putting a working solution to this question:
SELECT ... WHERE `myDateColumn` >= DATE(DATE_FORMAT(NOW(),'%Y-%m-%d'));
Obviously, you could change the NOW() function to any date or variable you want.
I solve this in my VB app with a simple tiny function (one line). Code taken out of a production app. The function looks like this:
Public Function MySQLDateTimeVar(inDate As Date, inTime As String) As String
Return "'" & inDate.ToString(format:="yyyy'-'MM'-'dd") & " " & inTime & "'"
End Function
Usage:
Let's say I have DateTimePicker1 and DateTimePicker2 and the user must define a start date and an end date. No matter if the dates are the same. I need to query a DATETIME field using only the DATE. My query string is easily built like this:
Dim QueryString As String = "Select * From SOMETABLE Where SOMEDATETIMEFIELD BETWEEN " & MySQLDateTimeVar(DateTimePicker1.Value,"00:00:00") & " AND " & MySQLDateTimeVar(DateTimePicker2.Value,"23:59:59")
The function generates the correct MySQL DATETIME syntax for DATETIME fields in the query and the query returns all records on that DATE (or BETWEEN the DATES) correctly.

How can I return results less than current date?

I want to return results from my table that have a date less than today's date. Here is my statement:
$today = date('Y-m-d');
SELECT * FROM events WHERE STR_TO_DATE('$today', '%Y-%m-%d') > wp_eventscalendar_main.eventStartDate
I can select events in the future without a problem but when I try to select events in the past I don't get any results. My column 'eventStartDate' is set as a Date. Is there some kind of special operator I should be using for this?
Thanks,
You probably need:
SELECT * FROM events WHERE CURDATE() > wp_eventscalendar_main.eventStartDate
MySQL tries to compare a String to a Date, which won't work reliably.
You can Use
select from table_name where date < curdate()

Select by Month of a field

How can I get records from my table using month/year? I have a table like this:
Name - varchar
DueDate -datetime
Status -boll
DueDate is project due date, I want record corresponding to month/year, not full date, I mean record for specific month.
How can I do this in mysql?
Simply use MONTH() and YEAR():
SELECT * FROM Project WHERE MONTH(DueDate) = 1 AND YEAR(DueDate) = 2010
You could use a between statement:
select * from Project
where DueDate between '2010-01-01' and '2010-02-01'
Do not use this here recommended solution with MONTH() and YEAR(). It prevents MySQL to use index on column DueDate if you have one and it forces MySQL to examine all rows in table.
Instead, use BETWEEN clause like this:
SELECT * FROM Project
WHERE DueDate BETWEEN '2010-01-01' AND '2010-02-01'
Or another solution with IN clause:
SELECT * FROM Project
WHERE DueDate IN ('2010-01-01', '2010-01-02', '2010-01-03', ..., '2010-01-31')
This two solutions allows MySQL to use index, so performance will be better.
SELECT Name FROM Table Where MONTH(datetime) = 1;
1 = January.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_month
it will select current year's specific month
SELECT * FROM Project WHERE MONTH(DueDate) = 1 AND YEAR(DueDate) = YEAR(NOW())
If you input month format "Y-m" you can use:
SELECT * FROM Project WHERE DATE_FORMAT(DueDate,"%Y-%m") = '2010-01'
You can extract the MONTH() and YEAR() for your DueDate.
SELECT * WHERE MONTH(DueDate) = '5' AND YEAR(DueDate) = '1987';
SELECT * FROM TABLE WHERE DueDate LIKE '2020-01%';
use in case you can substring your date data.