MySQL convert timestamp and time string to DateTime format - mysql

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.

Related

MySQL - How to convert date to the month has leading zeros?

So I'm trying to insert dates into a table and the date is in this format:
8/3/2021
However I want to add a leading 0 before the month and day so the date shows 08/03/2021. Also I want to add it as a string concatenated with another string so test123-08/03/2021
If you really store date in that format then you may try this:
SELECT
DATE_FORMAT(STR_TO_DATE(date_col_string,'%d/%m/%Y'),'%d/%m/%Y') as 'zero-padded',
CONCAT(string_val,'-',DATE_FORMAT(STR_TO_DATE(date_col_string,'%d/%m/%Y'),'%d/%m/%Y')) as 'concatenated'
FROM mytable;
Use STR_TO_DATE() function to change the date value to standard MySQL date format of YYYY-MM-DD then use DATE_FORMAT() function to display the date value as per your desired output. The second operation is adding CONCAT() function on the converted date with your selected string. I'm assuming that your date value is d/m/y, because as #Stu mentioned in the comment, since you're not storing as MySQL standard date format, that means 8/3/2021 can be either d/m/y or m/d/y. With a standard date format value, the query would be shorter:
SELECT
DATE_FORMAT(date_col,'%d/%m/%Y') as 'zero-padded',
CONCAT(string_val,'-',DATE_FORMAT(date_col,'%d/%m/%Y')) as 'concatenated'
FROM mytable;
Demo fiddle
You should be inserting your source dates into a proper date or datetime column. Then, to view your dates in the format you want, use the DATE_FORMAT() function with the appropriate format mask:
SELECT DATE_FORMAT(date_col, '%d/%m/%Y') AS date_out
FROM yourTable;

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

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.

Cannot scan the right values of Order date in sql

I want to fetch all datas that corresponds in the chosen date range.
So the problem is that. When theres included time in the data. It can't fetch the required data to be displayed. But when I remove the time on it. It displays really well. What can I do to make it right?
EXAMPLE VALUES:
2018-10-29 01:21:29pm
2018-10-30 01:21:29pm
EXAMPLE VALUES THAT WORKS:
2018-10-29
2018-10-30
My query:
`"SELECT *,SUBSTRING(order_date,1,10) from orders where order_date >='$fromdate' AND order_date <='$todate'"`
Ideal Solution: You will need to change the datatype of order_date from Varchar(500) to Datetime type, using Alter Table command.
Now, it is noteworthy that the MySQL datetime value is in YYYY-MM-DD HH:MM:SS format. So firstly, you will need to change your datetime string to MySQL datetime format string. Otherwise, directly changing the datatype will lead to irreparable loss/truncation of data.
Your datetime value 2018-10-29 01:21:29pm is basically of YYYY-MM-DD HH:MM:SS AM/PM (12 hour format). In terms of format specifiers, it would be: '%Y-%m-%d %h:%i:%s%p'. Complete list of available format specifiers can be seen in MySQL docs.
Firstly, we use Str_To_Date() function to convert all your data into proper Datetime format.
UPDATE orders
SET order_date = STR_TO_DATE(order_date, '%Y-%m-%d %h:%i:%s%p');
Now, next step is simple. Just modify the datatype to datetime:
ALTER TABLE orders
MODIFY COLUMN order_date datetime;

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 .

convert date from numeric value to date valid format

I need to filter all dates which greater than, say 01 january 2011.
select * from table_name where date > '01/01/2011';
the problem is that date field store int values, here is an example:
1339011098
1336717439
1339010538
How to convert the date field on the sql query (from the int format to date format), I need to convert it to a valid date so that I can compare it towards the above date.
Thanx.
You're going the wrong direction. Rather than converting potentially millions of records for the compare, try converting your target date, which you only need to do once. Those look like unix timestamps, so the resulting query should look like this:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('01/01/2011')
Or, if you can control this, try using the ISO date format, which avoids confusion with european date formats for dates like 3/2/13:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('2011-01-01')
You can use UNIX_TIMESTAMP()
select *
from table_name
where date > unix_timestamp('2011-01-01')
Or conversely use FROM_UNIXTIME()
select *
from table_name
where FROM_UNIXTIME(date, "%Y-%m-%d") > '2011-01-01'
First, you should not store date values as integers and if it's under your control your goal should be to fix the database and any queries that insert an integer value for that column instead of date.
The two date functions that you need to use with the current setup are UNIX_TIMESTAMP(), which accepts a date value and returns the epoch timestamp integer and FROM_UNIXTIME() which accepts an epoch timestamp integer and returns a date value.
For your example, you could use either:
SELECT * FROM table_name WHERE FROM_UNIXTIME(date_field) > '01/01/2011';
or
SELECT * FROM table_name WHERE date_field > UNIX_TIMESTAMP('01/01/2011');
But I would advise using FROM_UNIXTIME as a general rule as this would simplify more sophisticated queries such as:
SELECT * FROM table_name WHERE
FROM_UNIXTIME(date_field)
BETWEEN '01/01/2013' AND '04/01/2013';
Essentially, until your date field is actually storing values that are date types, your queries should covert the field values with FROM_UNIXTIME.