Home > Blockchain >  Change month, year, or day by input
Change month, year, or day by input

Time:11-16

I'm creating an application that calculates the days between 2 dates. I'm stuck at how I can change the value of Month when you type 12 or december. I cannot assign it to date1 because it is read only.

The input format is 13/12/2021 or 13/December/2021 (EU)

What currently is done is split the input by "/" or " " so I can assign the numbers to days/month/years.

My current code:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ', '/');
            string[] input2 = Console.ReadLine().Split(' ', '/');

            var date1 = new DateTime(2000, 3, 1, 7, 0, 0);

            for (int i = 0; i < input.Length; i  )
            {
                input[i] = input[i].ToLower();
            }

            for (int j = 0; j < input2.Length; j  )
            {
                input2[j] = input2[j].ToLower();
            }

            
            if (input[2] == "december") { date1.Month = 12; }

            foreach (var item in input)
            {
                Console.Write(item   " ");
            }
        }
    }
}

CodePudding user response:

You can't modify a DataTime (or any other Value Type). Instead you have to create a new one:

date1 = new DateTime(date1.Year, 12, date1.Day);

CodePudding user response:

Let's extract method for entring DateTime:

   public static DateTime ReadDate(string title) {
     // Keep asking until correct date has been provided
     while (true) {
       if (!string.IsNullOrEmpty(title)) 
         Console.WriteLine();

       // We support 13/12/2021, 13/December/2021 and 13/Dec/2021
       if (DateTime.TryParseExact(Console.ReadLine(), 
             new string[] { "d/M/yyyy", "d/MMMM/yyyy", "d/MMM/yyyy"}, 
             CultureInfo.InvariantCulture, 
             DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, 
             out var result)) 
         return result;

       Console.WriteLine("Syntax error. Please, try again."); 
     }  
   }

Then you can put it simple

   static void Main(string[] args) {
     DateTime date1 = ReadDate("Enter the first date."); 
     DateTime date2 = ReadDate("Enter the second date."); 

     TimeSpan difference = date2 - date1;

     Console.WriteLine($"Difference between {date1} and {date2} is {difference.TotalDays:f0} days"); 
   }
  •  Tags:  
  • c#
  • Related