How to use unix_timestamp( ) function on date comparison on string value - mysql

How to use unix_timestamp( ) function on date comparison on data type string that in a format of 1/1/2019. The goal is to show all the dates before 1/1/2010. Here is what I'm trying
SELECT
work_date
FROM
table
WHERE
work_date <= UNIX_TIMESTAMP('2010-01-01');

... date comparison on data type string that in a format of '1/1/2019'. The goal is to show all the dates before '1/1/2010'.
I don't really see why you would want to specifically use UNIX_TIMESTAMP() for that purpose. Basically you just need to convert your formated string to a date. For that, you can use STR_TO_DATE().
Consider:
SELECT work_date
FROM table
WHERE STR_TO_DATE(work_date, '%e/%c/%Y') <= '2010-01-01';
NB: it is impossible to tell if your string date format starts with the month or with the day; the above format stands for the second option, if you want it the other way around then that would be '%c/%e/%Y' instead.

Related

MySQL convert timestamp and time string to DateTime format

In my table have two columns, one as timestamp to save the date and one as time string to save the time with period.
Eg:
I want to combine them into one column as DateTime format in the result then order by desc on that column.
Here is the example: http://sqlfiddle.com/#!9/25eb21/4
The column name 'Datetime' expected is Datetime or timestamps type, so I can sort correctly on it.
You do not need to convert the values to integers to add them. MySQL has built-in functions for this purpose:
SELECT *,
addtime(apptDate, str_to_date(apptTime, '%h:%i %p')) as datetime
FROM appt
ORDER BY Datetime DESC;
If apptTime is just a time value (which it should be), then you obviously do not need to convert from a string. I would usuggest fixing the data model.
Let me assume that you want to add the duration that is stored as a string in column apptTime to timestamp in column apptDate.
A typical approach uses str_to_date() to turn the string to a datetime, then converts the time portion to seconds using time_to_sec(), which we can then add to the timestamp using date artihmetics.
So
select t.*
apptdate
+ interval time_to_sec(str_to_date(appttime, '%h:%i %p')) second
as newapptdate
from mytable
select addtime(appDate, appTime) from ...
Your appDate contains a time, probably because you are applying a timezone. Either convert your two columns to the timezone your data is supposed to be in with convert_tz(), or extract the date part of it with date(appDate) before you add it. It wasn't clear which of the columns was a string, but extract() or str_to_date() is the way to parse a text into a date and/or time.

How to convert a date string to mysql date format for calculating date diff using mysql query

I have a column where a date store in ddmmyy format (e.g. 151216). How can I convert it to yyyy-mm-dd format (e.g 2016-12-15) for calculating a date difference from the current date? I try using DATE_FORMAT function but its not appropriate for this.
If you want to get the date difference, you can use to_days() after converting the string to a date using str_to_date():
select to_days(curdate()) - to_days(str_to_date(col, '%d%m%y'))
or datediff():
select datediff(curdate(), str_to_date(col, '%d%m%y'))
or timestampdiff():
select timestampdiff(day, str_to_date(col, '%d%m%y'), curdate())
You can use the function, STR_TO_DATE() for this.
STR_TO_DATE('151216', '%d%m%y')
A query would look something like:
select
foo.bar
from
foo
where
STR_TO_DATE(foo.baz, '%d%m%y') < CURDATE()
Note: Since both STR_TO_DATE() and CURDATE() return date objects, there's no reason to change the actual display format of the date. For this function, we just need to format it. If you wanted to display it in your query, you could use something like
DATE_FORMAT(STR_TO_DATE(foo.baz, '%d%m%y'), '%Y-%m-%d')
To get the difference, we can simply subtract time
select
to_days(CURDATE() - STR_TO_DATE(foo.baz, '%d%m%y')) as diff
from
foo
If you wanted to only select rows that have a difference of a specified amount, you can put the whole to_days(...) bit in your where clause.
SELECT STR_TO_DATE('151216', '%d%m%y') FROM `table`
use this '%d%m%y'

select a date lesser than a particular date

I have stored the dates as string in my database.I know it is not good,but project already has been half developed before i take over and where dates were stored as string,so i was continuing the same way.
Now i want to select dates from table where date is greater than a specific date.
I tried the following query
SELECT
*
FROM
dates
where
STR_TO_DATE(date, '%Y-%m-%d') > "2014-01-01"
but it is not returning only greater values.
Please help me to solve problem.
Demo
Your dates are not in YYYY-MM-DD format. Use the right format!
SELECT *
FROM dates
where STR_TO_DATE(date, '%m-%d-%Y') > date('2014-01-01')
If you are going to store dates as strings, then the best way is in the ISO format of YYYY-MM-DD.
You should read the documentation on str_to_date() (here).
Convert everything to date and it should be fine. Now you are comparing date and string.
What type has the date? I'd prefer a ' instead of " for strings in SQL. Let's assume that date is a VARCHAR or TEXT field (depending on which database you are using):
SELECT *
FROM dates
WHERE STR_TO_DATE(date, '%Y-%m-%d') > STR_TO_DATE('2014-01-01', '%Y-%m-%d')
If date is a real DATE
SELECT *
FROM dates
WHERE trim(date) > STR_TO_DATE('2014-01-01', '%Y-%m-%d')
Or you just convert it into a number format date_format(date,'%Y%m%d') > 20140101

Read data stored as text and use in IF statement

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 select on date equality in a mySQL query?

I want to select rows from a table given a particular date of record in mysql
SELECT * from TABLENAME WHERE FROM_DATE='06/11/2012'
I am not getting anything useful.
First of all, you should use the standard date format Y-m-d - otherwise you have to make some nasty queries and sorting is a real b*tch.
Using the standard date format you can easily do something like this:
SELECT * FROM tablename WHERE from_date > '2012-06-11'
DATE comparisons are very likely what you want here. If your from_date column has the data type of DATE, then your code should be safe and robust if you do this:
WHERE from_date = STR_TO_DATE('06/11/2012', '%m/%d/%Y')
#Repox pointed out that you might consider putting your date literals in the canonical format '2012-06-11'. That's true, if you can do it. But STR_TO_DATE will do it for you if you need it to. There's a list of the %x conversion items here. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
If you're using DATETIME data types, beware: comparisons are more complex than they seem. DATETIME items are like floating point numbers: if one of them exactly equals another it's only by coincidence. That's because they represent moments (milliseconds) in time, not just days.
Presuming your from_date column has the DATETIME type, you should use
WHERE from_date >= STR_TO_DATE('06/11/2012', '%m/%d/%Y')
AND from_date < STR_TO_DATE('06/11/2012', '%m/%d/%Y') + INTERVAL 1 DAY
This will catch all moments in time on the day you want, up to but not including the first moment of the next day.
If your from_date items are represented as character strings, take the trouble to convert them to DATE or DATETIME data types. Seriously. Your results will be far better.
SELECT * from TABLENAME WHERE FROM_DATE='2012/06/13'
It would be better if you use the DATE() function of mysql
SELECT * FROM tablename WHERE DATE(from_date) > '2012-06-11'
Because, if the datatype of the from_date you set as TIMESTAMP or DATETIME then it won't return the correct results sometimes when you directly use the '>' symbol