Search code examples
c#htmlmaxblazor-server-side

Get a max attribute for input type date


I'm trying to limit my date input max attribute to be fluid so that it changes every year. Not hard-coded as it is now.

now: <input type="date" @bind-value="product.DateRetired" min="1950-01-01" max="2024-12-31" />

I've tried to break it down into:

  1. Get todays date (16/02/2023)
  2. add 1 year to that date (16/02/2024)
  3. return the last date of the new year (31/12/2024)
  4. change the format for the max attribute (2024-12-31)

attempt 1:

  <input type="date" @bind-value="product.DateRetired" min="1950-01-01" max="@GetNextYear-12-31" />

 private int GetNextYear()
    {
        DateTime thisyearaddone = DateTime.Today.AddYears(1);
        int nextyear = thisyearaddone.Year;
    
        return nextyear;
    }

attempt 2:

  <input type="date" @bind-value="product.DateRetired" min="1950-01-01" max="@GetNextYearDate" />

 private DateTime GetNextYear()
    {
        DateTime thisyearaddone = DateTime.Today.AddYears(1);
        int nextyear = thisyearaddone.Year;
        DateTime maxretireddate = new DateTime(nextyear, 12, 31);
        return maxretireddate;
    }

Attempt 3:

 public string MaxRetiredDate;

 <input type="date" @bind-value="product.DateRetired" min="1950-01-01" max="@MaxRetiredDate" onclick="@GetMaxRetiredDate" />

private void GetMaxRetiredDate()
    {
        DateTime NextYearDate = DateTime.Today.AddYears(1);
        int NextYearInt = NextYearDate.Year;
        DateTime MaxRetiredDate = new DateTime(NextYearInt, 12, 31);
        MaxRetiredDate.ToString("yyyy-mm-dd");
      
    }

Each attempt is unsuccessful and I can choose a date outside this range. Perhaps its to do with changing the formatting? How do I do this?


Solution

  • The entire thing could be condensed to 1 line of code:

     public string MaxRetiredDate = $"{(DateTime.Today.AddYears(1)).Year}-12-31";
    
    <input type="date" @bind-value="product.DateRetired" min="1950-01-01" max="@MaxRetiredDate" />