SQL Query to Convert Date to Datetime - GeeksforGeeks (2023)

snehalchitnis1851proficient9 published articles
  • Read
  • Discuss

    In this article, we will look at how to convert Date to Datetime. We can convert the Date into Datetime in two ways.

    • Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type.Convert() function is used to convert a value of any type to another datatype.
    • Using the CAST() function: SQL Server uses the CAST() function to cast or convert a value or an expression from one data type to another. The Cast() function is also used for the same purpose to convert the data type of any value.

    To perform any queries we have to create a database. So, let us create a database first.

    Step 1: Creating Database

    Query:

    CREATE DATABASE Test;

    Output:

    SQL Query to Convert Date to Datetime - GeeksforGeeks (2)

    Step 2: Converting Date to Datetime

    Method 1: Using CONVERT() function

    In this example, we are converting the date 01-01-2021 into Datetime. The date is in the form ‘yyyy-mm-dd’.

    Query:

    SELECT CONVERT(datetime, '2021-01-01');

    Output:

    SQL Query to Convert Date to Datetime - GeeksforGeeks (3)

    Method 2: Using CAST() function

    In this example, we are converting the date 01-01-2021 into Datetime as shown below. The date is in the form ‘yyyy-mm-dd’.

    Query:

    SELECT CAST('2021-01-01' AS datetime);

    Output:

    SQL Query to Convert Date to Datetime - GeeksforGeeks (4)

    Last Updated :18 Oct, 2021

    Like Article

    Save Article

    Top Articles
    Latest Posts
    Article information

    Author: Terrell Hackett

    Last Updated: 18/11/2023

    Views: 6143

    Rating: 4.1 / 5 (52 voted)

    Reviews: 91% of readers found this page helpful

    Author information

    Name: Terrell Hackett

    Birthday: 1992-03-17

    Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

    Phone: +21811810803470

    Job: Chief Representative

    Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

    Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.