简体   繁体   中英

How i can extract year from datetime.now?

I want user to input the year of vehicle made but not more than this year. for example today is 2015, i don't want them to input 2020. but 2016 is ok. here is my code.

    property = validationContext.ObjectType.GetProperty("VehicleYear");
    string vehicleYear = Convert.ToString(property.GetValue(validationContext.ObjectInstance, null));
    if (!string.IsNullOrWhiteSpace(vehicleYear) && vehicleYear.Length == 4 && Convert.ToInt16(vehicleYear) >= 1980)
    {
        isVehicleOlderThan1981 = true;
    }
    else
    {
        isVehicleOlderThan1981 = false;     
else if (value != null && Convert.ToDateTime(value) < DateTime.Now)
{
    return new ValidationResult(this.ErrorMessage);
}    

i only want to get a year from the DatetTime.now

Sorry i am new to the programming.

要获取任何日期(包括DateTime.Now)的年部分,请使用以下命令:

DateTime.Now.Year
else if (value != null && Convert.ToDateTime(value) > DateTime.Now.AddYears(10))
{
//validation error
}

Try this:

DateTime.Now.Year

You may also want to look at TryParse methods, it will simplify your code. ie

int i;
if(int.TryParse("VehicleYear", out i)
{
//successful conversion, use int i for your comparisons etc.
}
else
{
//wasn't a valid year (can't be converted)
}

You need to use Year Year property from DateTime . Your else if may look like:

else if (value != null && Convert.ToDateTime(value).Year < DateTime.Now.Year)

NOTE: Convert.ToDateTime(value).Year will scream at you if value does not have correct date.

I tried to clean your code for a bit and make it more logical (Also attached the answer you are looking for):

    property = validationContext.ObjectType.GetProperty("VehicleYear");
    var value = property.GetValue(validationContext.ObjectInstance, null);
    int inputNumber;
    //First check if input is number
    if (!int.TryParse(value, out inputNumber))
    {
      this.ErrorMessage = "Input is not an integer!"
      //you could also throw an exception here (depends on your error handling)
      return new ValidationResult(this.ErrorMessage);
    }

   //retrieves the number of digits
    int countDigits = Math.Floor(Math.Log10(year) + 1);
    if (countDigits != 4)
    {
      this.ErrorMessage = String.Format("Input has {0} digits!",countDigits);
      return new ValidationResult(this.ErrorMessage);
    }

    if (inputNumber > (DateTime.Now.Year + 1))
    {
      this.ErrorMessage = "Year is in the future!";
      return new ValidationResult(this.ErrorMessage);
    }

    //inputNumber is now a valid year!
    if(inputNumber > 1980)
    {
       isVehicleOlderThan1981 = true;
    } else {
       isVehicleOlderThan1981 = false;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM