DEV Community

Rajesh Verma
Rajesh Verma

Posted on • Edited on

Mastering Date and Time in C#: A Practical Developer’s Guide

Working with DateTime in C# is something every developer eventually has to do — whether it's logging timestamps, showing the current date, or formatting values for user interfaces or APIs.

In this post, I’ll walk you through some key ways to work with DateTime, from creation and formatting to parsing and real-world tips. If you want the complete cheat sheet with 50+ examples, you can check out this full guide I wrote recently.

🔹 Getting the Current Date and Time

DateTime now = DateTime.Now;       // Local time
DateTime utc = DateTime.UtcNow;    // UTC time
Enter fullscreen mode Exit fullscreen mode

🔹 Formatting DateTime Output
You can use both standard and custom formats to display a DateTime as a string.

DateTime dt = DateTime.Now;

string formatted1 = dt.ToString("yyyy-MM-dd");         // 2025-04-28
string formatted2 = dt.ToString("dddd, MMMM dd yyyy"); // Monday, April 28 2025
Enter fullscreen mode Exit fullscreen mode

🔹 Parsing Strings to DateTime

string input = "04/28/2025";
DateTime parsed = DateTime.Parse(input);  // Careful: throws if input is invalid

// Safer:
if (DateTime.TryParse(input, out DateTime result))
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("Invalid date format.");
}
Enter fullscreen mode Exit fullscreen mode

🔹 Adding and Subtracting Dates

DateTime today = DateTime.Today;
DateTime nextWeek = today.AddDays(7);
DateTime lastMonth = today.AddMonths(-1);
Enter fullscreen mode Exit fullscreen mode

Bonus: C# DateTime Cheat Sheet (50+ Examples)

If you’re looking for a complete breakdown of format codes (yyyy, MM, dd, tt, etc.) and examples of parsing, time zones, and culture-specific formatting — I’ve compiled it all in this detailed C# DateTime formatting guide. Bookmark it for reference, especially if you’re working with international users or APIs

Final Thoughts
Mastering DateTime in C# isn’t hard once you understand formatting and parsing. Try to use TryParse whenever you're dealing with user input, and keep a formatting reference handy.

Let me know in the comments how you handle time zones or if you use DateTimeOffset in your projects!

Top comments (0)