DateTime format to SQL format using C#

DateTime format to SQL format using C#

To convert the date and time from normal format to SQL standard format (YYYY-MM-DD HH:MM: SS) using C#, we have to use the ToString() function. In this blog, we will learn how we can do the above operation in more detail:

Table of Contents:

C# Program to convert DateTime format to SQL format

Let’s have a look at the below program, and how we convert DateTime Format to SQL format in C#:

Syntax:

string sqlFormattedDate = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");

Program:

using System;
class Program
{
    static void Main()
    {
        DateTime currentDateTime = DateTime.Now;
          Console.WriteLine("DateTime in Normal format: " + currentDateTime);
        string sqlFormattedDate = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");
        Console.WriteLine("DateTime in SQL format: " + sqlFormattedDate);
    }
}

Output:

DateTime in Normal format: 01/24/2025 10:52:51
DateTime in SQL format: 2025-01-24 10:52:51

Explanation: with the help of ToString() function, we can convert the DateTime Format to SQL format.

Conclusion

So far in this article, we have learned how to convert the DateTime Format to SQ format using C#.  C# is a modern, object-oriented programming language designed specifically for the .NET framework. If you want to learn more about .NET, you may refer to our .NET course.

About the Author

Data Engineer

As a skilled Data Engineer, Sahil excels in SQL, NoSQL databases, Business Intelligence, and database management. He has contributed immensely to projects at companies like Bajaj and Tata. With a strong expertise in data engineering, he has architected numerous solutions for data pipelines, analytics, and software integration, driving insights and innovation.

business intelligence professional