How to Add or Subtract Days, Months, or Years from a Date in C#

Manipulating dates is a common task in C# applications, whether for scheduling, logging, or calculations.

The DateTime and DateOnly structures provide built-in methods to add or subtract days, months, years, hours, and minutes efficiently.

Adding and Subtracting Days

Use the AddDays method to modify a DateTime instance:

using System;

class Program
{
    static void Main()
    {
        DateTime today = DateTime.Now;
        DateTime nextWeek = today.AddDays(7);
        DateTime lastWeek = today.AddDays(-7);

        Console.WriteLine($"Today: {today:yyyy-MM-dd HH:mm}");
        Console.WriteLine($"Next Week: {nextWeek:yyyy-MM-dd HH:mm}");
        Console.WriteLine($"Last Week: {lastWeek:yyyy-MM-dd HH:mm}");
    }
}

Adding and Subtracting Months

Use the AddMonths method to adjust the month while automatically handling month-end variations:

DateTime currentDate = new DateTime(2025, 3, 31);
DateTime nextMonth = currentDate.AddMonths(1);
DateTime previousMonth = currentDate.AddMonths(-1);

Console.WriteLine($"Current Date: {currentDate:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Next Month: {nextMonth:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Previous Month: {previousMonth:yyyy-MM-dd HH:mm}");

Adding and Subtracting Years

Use the AddYears method to adjust the year, handling leap years automatically:

DateTime date = new DateTime(2024, 2, 29);
DateTime nextYear = date.AddYears(1);
DateTime previousYear = date.AddYears(-1);

Console.WriteLine($"Original Date: {date:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Next Year: {nextYear:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Previous Year: {previousYear:yyyy-MM-dd HH:mm}");

Adding and Subtracting Hours

Use the AddHours method to modify the hour component:

DateTime now = DateTime.Now;
DateTime inFiveHours = now.AddHours(5);
DateTime fiveHoursAgo = now.AddHours(-5);

Console.WriteLine($"Current Time: {now:yyyy-MM-dd HH:mm}");
Console.WriteLine($"In 5 Hours: {inFiveHours:yyyy-MM-dd HH:mm}");
Console.WriteLine($"5 Hours Ago: {fiveHoursAgo:yyyy-MM-dd HH:mm}");

Adding and Subtracting Minutes

Use the AddMinutes method to modify the minute component:

DateTime currentTime = DateTime.Now;
DateTime inThirtyMinutes = currentTime.AddMinutes(30);
DateTime thirtyMinutesAgo = currentTime.AddMinutes(-30);

Console.WriteLine($"Current Time: {currentTime:yyyy-MM-dd HH:mm}");
Console.WriteLine($"In 30 Minutes: {inThirtyMinutes:yyyy-MM-dd HH:mm}");
Console.WriteLine($"30 Minutes Ago: {thirtyMinutesAgo:yyyy-MM-dd HH:mm}");

Using DateOnly for Simpler Date Manipulation

For applications that don't require time components, DateOnly (introduced in .NET 6) provides a cleaner approach:

DateOnly today = DateOnly.FromDateTime(DateTime.Now);
DateOnly futureDate = today.AddDays(30);

Console.WriteLine($"Today: {today}");
Console.WriteLine($"30 Days Later: {futureDate}");

Conclusion

C# provides built-in methods for adjusting dates effortlessly. Whether working with DateTime or DateOnly, these functions ensure accurate date calculations, even when dealing with leap years, month-end scenarios, hours, and minutes.

0
196

Related

When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.

Using COUNT(DISTINCT column_name)

To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:

SELECT COUNT(DISTINCT column_name) AS distinct_count
FROM table_name;

This query will return the number of unique values in column_name.

Counting Distinct Values Across Multiple Columns

If you need to count distinct combinations of multiple columns, you can use a subquery:

SELECT COUNT(*) AS distinct_count
FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;

This approach ensures that only unique pairs of column1 and column2 are counted.

Why Use COUNT DISTINCT?

  • Helps in identifying unique entries in a dataset.
  • Useful for reporting and analytics.
  • Efficient way to check for duplicates.

By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!

0
104

Reading a file line by line is useful when handling large files without loading everything into memory at once.

✅ Best Practice: Use File.ReadLines() which is more memory efficient.

Example

foreach (string line in File.ReadLines("file.txt"))
{
    Console.WriteLine(line);
}

Why use ReadLines()?

Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).

Alternative: Use StreamReader (More Control)

For scenarios where you need custom processing while reading the contents of the file:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string? line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Why use StreamReader?

Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).

When to Use ReadAllLines()? If you need all lines at once, use:

string[] lines = File.ReadAllLines("file.txt");

Caution: Loads the entire file into memory—avoid for large files!

3
248

XML (Extensible Markup Language) is a widely used format for storing and transporting data.

In C#, you can create XML files efficiently using the XmlWriter and XDocument classes. This guide covers both methods with practical examples.

Writing XML Using XmlWriter

XmlWriter provides a fast and memory-efficient way to generate XML files by writing elements sequentially.

Example:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        using (XmlWriter writer = XmlWriter.Create("person.xml"))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Person");

            writer.WriteElementString("FirstName", "John");
            writer.WriteElementString("LastName", "Doe");
            writer.WriteElementString("Age", "30");

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
        Console.WriteLine("XML file created successfully.");
    }
}

Output (person.xml):

<?xml version="1.0" encoding="utf-8"?>
<Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Age>30</Age>
</Person>

Writing XML Using XDocument

The XDocument class from LINQ to XML provides a more readable and flexible way to create XML files.

Example:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        XDocument doc = new XDocument(
            new XElement("Person",
                new XElement("FirstName", "John"),
                new XElement("LastName", "Doe"),
                new XElement("Age", "30")
            )
        );
        doc.Save("person.xml");
        Console.WriteLine("XML file created successfully.");
    }
}

This approach is ideal for working with complex XML structures and integrating LINQ queries.

When to Use Each Method

  • Use XmlWriter when performance is critical and you need to write XML sequentially.
  • Use XDocument when you need a more readable, maintainable, and flexible way to manipulate XML.

Conclusion

Writing XML files in C# is straightforward with XmlWriter and XDocument. Choose the method that best suits your needs for performance, readability, and maintainability.

1
126