- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert from varchar to datetime and compare in MySQL?
For this, you can use STR_TO_DATE(). Let us first create a table −
mysql> create table DemoTable1565 -> ( -> ArrivalDatetime varchar(40) -> ); Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1565 values('10/01/2019 21:29:35'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1565 values('10/13/2019 4:56:00'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1565 values('10/13/2018 12:40:46'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1565 values('10/13/2019 21:30:00'); Query OK, 1 row affected (0.58 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1565;
This will produce the following output −
+---------------------+ | ArrivalDatetime | +---------------------+ | 10/01/2019 21:29:35 | | 10/13/2019 4:56:00 | | 10/13/2018 12:40:46 | | 10/13/2019 21:30:00 | +---------------------+ 4 rows in set (0.00 sec)
The current date is as follows −
mysql> select now(); +---------------------+ | now() | +---------------------+ | 2019-10-13 21:34:14 | +---------------------+ 1 row in set (0.00 sec)
Here is the query to convert from varchar to datetime and compare −
mysql> select * from DemoTable1565 where str_to_date(ArrivalDatetime,'%m/%d/%Y')=curdate();
This will produce the following output −
+---------------------+ | ArrivalDatetime | +---------------------+ | 10/13/2019 4:56:00 | | 10/13/2019 21:30:00 | +---------------------+ 2 rows in set, 4 warnings (0.03 sec)
Advertisements