To avoid label of duplicate here's a brief summary of all what i did.
After spending hours of googling to calculate the difference between two dates I came across here and here where, i was convinced to use NodaTime to get difference in terms of years,months and days.My application needs accuracy to calculate pension.I used datetimepicker
to get the date value from form and then i use Date.cs
from here to extract the date in dd/mm/year
and then insert it into database.To subtract the two dates using Period.Between(date1, date2, PeriodUnits.Years).Years
how should i pass datetimepicker
to it?
Here's what Jon Skeet said: "you can use LocalDateTime.FromDateTime
and then use the Date
property to get a LocalDate
".
How should i get a complete rid of time while inserting in database as well as finding the difference while using datetimepicker
instead of Datetime
.
Update:
//Date of appointment
var d_app = LocalDateTime.FromDateTime(dateTimePicker1.Value).Date;
//Date of retirement
var d_ret = LocalDateTime.FromDateTime(dateTimePicker2.Value).Date;
var years=Period.Between(d_app,d_ret,PeriodUnits.Years).Years;
var months = Period.Between(d_app, d_ret, PeriodUnits.Months).Months;
var days = Period.Between(d_app, d_ret, PeriodUnits.Days).Days;
MessageBox.Show(years.ToString()+" years"+months.ToString()+"months "+days.ToString()+"days");
Giving the code datetimepicker1.value
as 2/21/1990
(d_app) and datetimepicker2.value
as 3/09/2015
(d_ret) it returned 25 yrs 300months 9147
days
.
What am i doing wrong?
You're performing three separate computations here. You only need one:
var appointment = LocalDateTime.FromDateTime(dateTimePicker1.Value).Date;
var retirement = LocalDateTime.FromDateTime(dateTimePicker2.Value).Date;
var difference = Period.Between(appointment, retirement);
MessageBox.Show(string.Format("{0} years {1} months {2} days",
difference.Years, difference.Months, difference.Days));
See more on this question at Stackoverflow