Need help to calculate number of years in Razor code.

• Question

• User-1590744680 posted

Hi ,

I need to calculate number of years between current date and specified field in database in Razor. We use razor code to build email content.

I'm looking for something like:

@Convert.ToInt32((DateTime.Now - (Convert.ToDateTime(Model.Listings[0].LatestSubscriptionEndDate))).Years) Years

but this is not working..

Monday, October 29, 2018 3:49 PM

All replies

• User-1590744680 posted

I was able to figure out years part . I need to calculate it only for values which exist only for month of november.

@Convert.ToInt32(((DateTime.Now - (Convert.ToDateTime(Model.FirstLiveDate))).TotalDays)/365)

Monday, October 29, 2018 4:53 PM
• User-271186128 posted

Hi cVishal259,

I was able to figure out years part . I need to calculate it only for values which exist only for month of november.

@Convert.ToInt32(((DateTime.Now - (Convert.ToDateTime(Model.FirstLiveDate))).TotalDays)/365)

It seems that you have already solved the problem. You could also refer to the following code to calculate the time span:

` @Convert.ToInt32((DateTime.Now.Year - (Convert.ToDateTime(Model.LatestSubscriptionEndDate).Year))) Years`

or

```        @{
var timespan = DateTime.Now - (Convert.ToDateTime(Model.LatestSubscriptionEndDate));
var tempdate = DateTime.MinValue + timespan;
var year = tempdate.Year - 1;
var month = tempdate.Month - 1;
var day = tempdate.Day - 1;
}
@year  Years @month Months @day Days ago```

Best regards,
Dillion

Tuesday, October 30, 2018 3:20 AM