C# Code that Prints the Date and Time in Various Formats

C# Code that Prints the Date and Time in Various Formats

This is a simple C# program that returns the current date and time in various formats. This program uses the DateTime.Now property to get the current date and time. This C# code has separate function that takes a DateTime object and a date/time format as parameters and returns the formatted date/time string. The Main function then passes various date/time formats to this function and prints the results:

using System;

class Program
{
    static void Main()
    {
        // Get the current date and time
        DateTime currentDate = DateTime.Now;

        // Pass various date/time formats to the function and print the results
        PrintFormattedDateTime(currentDate, "G"); // General date/time (short time)
        PrintFormattedDateTime(currentDate, "F"); // Full date/time (long time)
        PrintFormattedDateTime(currentDate, "D"); // Long date
        PrintFormattedDateTime(currentDate, "d"); // Short date
        PrintFormattedDateTime(currentDate, "T"); // Long time
        PrintFormattedDateTime(currentDate, "t"); // Short time
        PrintFormattedDateTime(currentDate, "yyyy-MM-dd HH:mm:ss"); // Custom format

        Console.ReadLine(); // Pause to see the output
    }

    static void PrintFormattedDateTime(DateTime dateTime, string format)
    {
        string formattedDateTime = GetFormattedDateTime(dateTime, format);
        Console.WriteLine($"Formatted Date/Time ({format}): {formattedDateTime}");
    }

    static string GetFormattedDateTime(DateTime dateTime, string format)
    {
        return dateTime.ToString(format);
    }
}

In this code, the PrintFormattedDateTime function takes a DateTime object and a date/time format as parameters, and it prints the formatted date/time string using the GetFormattedDateTime function. The GetFormattedDateTime function takes the same parameters and returns the formatted date/time string using the ToString method with the specified format.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post