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.