search

Home  >  Q&A  >  body text

Get the maximum attribute of 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 like now.

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

I try to break it down into:

  1. Get today’s date (16/02/2023)
  2. Add 1 year to this date (February 16, 2024)
  3. Return the last date of the new year (31/12/2024)
  4. Change the format of 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");
      
    }

Every time I try without success, I can select a date outside of this range. Maybe something to do with changing the format? what should I do?

P粉676588738P粉676588738265 days ago413

reply all(1)I'll reply

  • P粉005105443

    P粉0051054432024-03-31 14:27:20

    The whole thing can be condensed into 1 line of code:

    public string MaxRetiredDate = $"{(DateTime.Today.AddYears(1)).Year}-12-31";
    
    

    reply
    0
  • Cancelreply