C# compare two DateTimes

前端 未结 6 1390
深忆病人
深忆病人 2021-01-02 00:34

I have two dates:

DateTime date_of_submission = Convert.ToDateTime(DateTime.Now.ToString(\"MM/dd/yyyy\"));
DateTime _effective_date = Convert.ToDateTime(Text         


        
相关标签:
6条回答
  • 2021-01-02 00:57

    You can compare two datetime values with each other as you normally compare.

    So, you can do the following :-

    if(date_of_effective_date.CompareTo(date_of_submission_date.AddDays(90)) <= 0)
    {
     //Correct
    }
    
    0 讨论(0)
  • 2021-01-02 01:02

    You can subtract two dates, and get a TimeSpan :

    TimeSpan difference = _effective_date - date_of_submission;
    if(difference.TotalDays > 90)
    {
      // Bingo!
    }
    
    0 讨论(0)
  • 2021-01-02 01:05

    Something like...

            TimeSpan difference = _effective_date - date_of_submission;
            double days = difference.TotalDays;
    
            if (days > 0 && days <= 90)
            {
                //valid
            }
    
    0 讨论(0)
  • 2021-01-02 01:08

    Though there are several effective solution, It could be one for future searchers

    DateTime date_of_submission = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"));
    DateTime _effective_date = Convert.ToDateTime(TextBox32.Text);
    
    DateTime lastPossibleEffectiveDate = _effective_date.AddDays(90);
    
    int result = DateTime.Compare(_effective_date,lastPossibleEffectiveDate);
    if (result <= 0)
        Console.WriteLine("Valid Date");
    else if (result > 0 )
        Console.WriteLine("Not Valid effective date");
    
    0 讨论(0)
  • 2021-01-02 01:19
    var days = (_effective_date - date_of_submission).Days;
    
    0 讨论(0)
  • 2021-01-02 01:19

    This is a sample to compare datetime. you can change according to your requirement

     DateTime dtFromDate = DateTime.ParseExact(TextBoxFromDate.Text, "dd/MM/yyyy",
                                                       CultureInfo.InvariantCulture);
     DateTime dtToDate = DateTime.ParseExact(TextBoxToDate.Text, "dd/MM/yyyy",
                                                       CultureInfo.InvariantCulture);
     TimeSpan difference = dtFromDate - dtToDate;
     double days = difference.TotalDays;
    
     if (days > 0)
     {
       DivFormError.InnerText = "“From Date” cannot be greater than “To Date”";
     }
    
    0 讨论(0)
提交回复
热议问题