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
383

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
110

Storing passwords as plain text is dangerous. Instead, you should hash them using a strong, slow hashing algorithm like BCrypt, which includes built-in salting and resistance to brute-force attacks.

Step 1: Install BCrypt NuGet Package

Before using BCrypt, install the BCrypt.Net-Next package:

dotnet add package BCrypt.Net-Next

or via NuGet Package Manager:

Install-Package BCrypt.Net-Next

Step 2: Hash a Password

Use BCrypt.HashPassword() to securely hash a password before storing it:

using BCrypt.Net;

string password = "mySecurePassword123";
string hashedPassword = BCrypt.HashPassword(password);

Console.WriteLine(hashedPassword); // Output: $2a$12$...

Step 3: Verify a Password

To check a user's login attempt, use BCrypt.Verify():

bool isMatch = BCrypt.Verify("mySecurePassword123", hashedPassword);
Console.WriteLine(isMatch); // Output: True

Ensuring proper hashing should be at the top of your list when it comes to building authentication systems.

2
249

When working with large files, reading the entire file at once may be inefficient or unnecessary, especially when you only need the first few lines.

In C#, you can easily read just the first N lines of a file, improving performance and resource management.

Why Read Only the First N Lines?

Reading only the first few lines of a file can be beneficial for:

  • Quickly checking file contents or formats.
  • Processing large files without consuming excessive memory.
  • Displaying previews or samples of file content.

Reading the First N Lines with StreamReader

Here's a simple and efficient method using C#:

using System;
using System.IO;

class FileReader
{
    /// <summary>
    /// Reads the first N lines from a file.
    /// </summary>
    /// <param name="filePath">The path to the file.</param>
    /// <param name="numberOfLines">Number of lines to read.</param>
    /// <returns>Array of strings containing the lines read.</returns>
    public static string[] ReadFirstNLines(string filePath, int numberOfLines)
    {
        List<string> lines = new List<string>();

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            int counter = 0;

            // Read lines until the counter reaches numberOfLines or EOF
            while (counter < numberOfLines && (line = reader.ReadLine()) != null)
            {
                lines.Add(line);
                counter++;
            }
        }

        return lines.ToArray();
    }

Example Usage

Here's a practical example demonstrating the usage of the method above:

string filePath = "C:\\largefile.txt";
int linesToRead = 10;

string[] firstLines = FileReader.ReadFirstNLines(filePath, firstLinesCount);

foreach (string line in firstLines)
{
    Console.WriteLine(line);
}

Efficient and Shorter Alternative with LINQ

For a concise implementation, LINQ can also be used:

using System;
using System.IO;
using System.Linq;

class FileReader
{
    public static IEnumerable<string> ReadFirstNLines(string filePath, int numberOfLines)
    {
        // Take first N lines directly using LINQ
        return File.ReadLines(filePath).Take(numberOfLines);
    }
}

Usage Example with LINQ Method:

string path = "C:\\largeFile.txt";
int n = 10;

var lines = FileReader.ReadFirstNLines(path, n);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

Best Practices

  • Use File.ReadLines instead of File.ReadAllLines for large files, as it does not load the entire file into memory.
  • Always handle exceptions properly to ensure your application remains stable.
  • For large files, avoid methods like ReadAllLines() which can negatively affect performance.

Final Thoughts

By limiting your reading operations to only the first few lines you actually need, you significantly enhance your application's efficiency and resource management.

0
172