I would like to compare 2 dates to confirm that the number of years between is >= 18. For example, if my 2 dates are 03-12-2011 and 03-12-1983 then this should pass validation, however, if my 2 dates are 03-12-2011 and 03-12-1995 then this should fail validation.
Can anyone help me?
hope this is what you are looking for
public bool CheckDate(DateTime date1, DateTime date2)
{
return date1.AddYears(-18) < date2;
}
I re-jigged your question title & description to make it a bit more clear. From what I gathered from your original post you are looking for an Age Verification function. Here is what I would do:
function VerifyAge(DateTime dateOfBirth)
{
DateTime now = DateTime.Today;
int age = now.Year - dateOfBirth.Year;
if (now.Month < dateOfBirth.Month || (now.Month == dateOfBirth.Month && now.Day < dateOfBirth.Day))
age--;
return age >= 18;
}
Use TimeSpan structure.
TimeSpan span= dateSecond - dateFirst;
int days=span.Days;
//or
int years = (int) (span.Days / 365.25);
Check the TimeSpan structure:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx
Use Timespan:
TimeSpan day = 03-12-2011 - 03-12-1983;
double year = day.TotalDays / 365.25;
if (year > 18)
{
}
Maybe instead of 03-12-2011 you should use DateTime.Now
Here's a method to check if the age is more than 18:
private bool IsMoreThan18(DateTime from, DateTime to)
{
int age = to.Year - from.Year;
if (from > to.AddYears(-age)) age--;
return age >= 18;
}
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2008, 1, 1);
DateTime b = new DateTime(2016, 1, 1);
TimeSpan span = b - a;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
Console.WriteLine("Years elapsed: " + years);
Refrence Link
Try this....
Using this you can get the exact no of years between two days. Only you need to do is divide the date difference by 365.25
TimeSpan span = DateTime.Parse(To_Date) - DateTime.Parse(From_Date);
int years = (int)(span.Days / 365.25);
Create two DateTime objects and substract them from eachother.
The result is a DateTime object aswel:
DateTime dt = new DateTime(2011, 12, 03);
DateTime dt2 = new DateTime(1983, 12, 03);
DateTime dt3 = dt - dt2;
Now you can check dt3.Year for the number of years between them
Related
I got here a scenario where I input an information but the code does does not work. What happen is when I input 12/11/2015, the Address2Panel shows. Which is wrong because there no more date that I can input because Person A is born in 12/11/2015. The logic should Enter addresses for the past 5 years. But it goes wrong if the Birthdate gap is not lesser the 5 years from the current date.
Person A Birthday = 12/11/2015
Person A StartLiving = 12/11/2015 because its the day he/she was born.
Should not display Address2Panel
int CurrentDateInMonths = (((DateTime.Today.Year) * 12) + (DateTime.Today.Month));
static int AlienMonthsAtCurrentAddress = 0;
DateTime myDateTime;
//LivedHere = 12/11/2015
myDateTime = DateTime.Parse(LivedHere.Text);
AlienMonthsAtCurrentAddress = (CurrentDateInMonths - (((Convert.ToInt16(myDateTime.Year)) * 12) + Convert.ToInt16(myDateTime.Month)));
if (AlienMonthsAtCurrentAddress < 60)
{
Address2Panel.Visible = true;//shows the Address2Panel
}
else
{
ClearAddress2Panel();//hides also the Address2Panel
}
Any suggestion how should I improve my formula and date time manipulation?
no need to convert date into months, subtract dates using DateTime.Subtract method :
From MSDN, DateTime.Subtract Method subtracts the specified date and time from this instance.It returns a TimeSpan object which has a property Days
static int AlienMonthsAtCurrentAddress = 0;
try
{
DateTime myDateTime;
myDateTime = DateTime.Parse(LivedHere.Text);
// If you don't wish to subtract from today's date use required date in place of DateTime.Now
TimeSpan span = DateTime.Now.Subtract ( myDateTime );
if (span.Days < 60)
{
Address2Panel.Visible = true;//shows the Address2Panel
}
else
{
ClearAddress2Panel();//hides also the Address2Panel
}
}
catch { }
You could check years, months and days with a separately logic, and then get them all together:
DateTime date = new DateTime(2015,11,12)
DateTime input = getDate()
int years = input.Year - date.Year - 1
years += If(input.Month > date.Month, 1, 0)
years += If(input.Month = date.Month AndAlso input.Day >= date.Day, 1, 0)
This will output the exact number of years between two days (truncating the resulting integer). You'll just have to compare it to 5, in your case
In a scenario where you would need to calculate the next 'Billing date' if the DAY (2nd, 25th, etc) is known, how can you calculate the number of days left until the next bill payment?
Explanation:
Tom's bill gets generated on the 4th of every month
What's the best way/logic to calculate the days left until the next bill? For example, if today is the 28th of this month, the result would be 6 days left
What we know:
Bill Generation Date is known
Today's Date is known
What I've done so far:
int billingDay = 4; //The day the bill gets generated every month
DateTime today = DateTime.Today; //Today's date
How would I continue this to calculate the next billing date?
P.S: Sorry if this sounds lame, I just couldn't wrap my head around it :)
I think this works:
private int GetNumDaysToNextBillingDate(int billingDayOfMonth)
{
DateTime today = DateTime.Today;
if (today.Day <= billingDayOfMonth)
{
return (new DateTime(today.Year, today.Month, billingDayOfMonth) - today).Days;
}
else
{
var oneMonthFromToday = today.AddMonths(1);
var billingDateNextMonth =
new DateTime(oneMonthFromToday.Year,
oneMonthFromToday.Month, billingDayOfMonth);
return (billingDateNextMonth - today).Days;
}
}
How about:
int billingDay = 4;
DateTime today = DateTime.UtcNow;
DateTime billing = today.Day >= billingDay
? new DateTime(today.AddMonths(1).Year, today.AddMonths(1).Month, billingDay)
: new DateTime(today.Year, today.Month, billingDay);
TimeSpan left = billing - today;
This uses a loop but is less prone to error as it takes into account month and year changes:
int DaysUntilBilling(int billingDay, DateTime referenceDate)
{
int count = 0;
while (referenceDate.AddDays(count).Day != billingDay)
{
count++;
};
return count;
}
You of course don't need to pass a DateTime in as an argument if you are always using today's date, but this helps to test that that for different inputs, you get the desired output:
int billingDay = 4;
DaysUntilBilling(billingDay, DateTime.Now); //26 (today is 9th Aug 2016)
DaysUntilBilling(billingDay, new DateTime(2016, 09, 03); //1
DaysUntilBilling(billingDay, new DateTime(2016, 09, 04); //0
DaysUntilBilling(billingDay, new DateTime(2016, 08, 05); //30
DaysUntilBilling(billingDay, new DateTime(2016, 12, 19); //16
This link might help you :
https://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth(v=vs.110).aspx
What you can do is something like this:
int daysUntilBill = 0;
int billingDay = 4;
DateTime today = DateTime.Today;
if (billingDay > today.Day) {
daysUntilBill = billingDay - today.Day;
} else {
int daysLeftInMonth = DateTime.DaysInMonth(today.Year, today.Month) - today.Day;
daysUntilBill = billingDay + daysLeftInMonth;
}
or slightly more concise
int daysUntilBill = (billingDay >= today.Day)
? billingDay - today.Day
: billingDay + DateTime.DaysInMonth(today.Year, today.Month) - today.Day;
This properly handles the year ending too, since it doesn't try to wrap around.
First you need to determine if the current date is on or before the billing day and if it is just subtract the current day of the month. Otherwise you have to determine the next billing date in the following month.
public int DaysToNextBill(int billingDay)
{
var today = DateTime.Today;
if(today.Day <= billingDay)
return billingDay - today.Day;
var nextMonth = today.AddMonth(1);
var nextBillingDate = new DateTime(nextMonth.Year, nextMonth.Month, billingDay)
return (nextBillingDate - today).Days;
}
The only thing left to deal with is if billingDay is greater than the number of days in the current or following month.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating age from birthday
How do you calculate age in years, taking input from TextBox in the format dd/MM/yyyy?
e.g.
input: txtDOB.Text 20/02/1989 (String format)
output: txtAge.Text 23
You can use the Substract method of DateTime (link) and then use the Days property to determine the actual age:
DateTime now = DateTime.Now;
DateTime givenDate = DateTime.Parse(input);
int days = now.Subtract(givenDate).Days
int age = Math.Floor(days / 365.24219)
TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20);
double Years = TS.TotalDays / 365.25; // 365 1/4 days per year
As already noted in a comment, the correct answer is here: Calculate age in C#
You just need to get the birthday as a DateTime:
DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
The following will work once you have parsed the birth date into a DateTime:
static int AgeInYears(DateTime birthday, DateTime today)
{
return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}
Parse the date like so:
DateTime dob = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
And a sample program:
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
DateTime dob = new DateTime(2010, 12, 30);
DateTime today = DateTime.Now;
int age = AgeInYears(dob, today);
Console.WriteLine(age); // Prints "1"
}
static int AgeInYears(DateTime birthday, DateTime today)
{
return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}
}
}
This answer isn't the most efficient as it uses a loop, but it doesn't rely on using 365.25 magic numbers either.
A function to return the whole number of years from a datetime to today:
public static int CalcYears(DateTime fromDate)
{
int years = 0;
DateTime toDate = DateTime.Now;
while (toDate.AddYears(-1) >= fromDate)
{
years++;
toDate = toDate.AddYears(-1);
}
return years;
}
Usage:
int age = CalcYears(DateTime.ParseExact(txtDateOfBirth.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture));
var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var age = (DateTime.Today.Year - date.Year);
Console.WriteLine(age);
Try this
string[] AgeVal=textbox.text.split('/');
string Year=AgeVal[2].tostring();
string CurrentYear= DateTime.Now.Date.Year.ToString();
int Age=Convert.ToInt16((Current))-Convert.ToInt16((Year));
Subtract the two values and get your age.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I calculate someone's age in C#?
how do I calculate what a persons age will be on a given date?
I have the date of birth, and for what I am doing now, the date I want to calculate it for is the end of the year e.g. 31/12/2012 23:59:59.
How can I calculate from these variables how many years old a person will be at the end of the year?
Thanks.
Subtract the years from the target date and the birth date; subtract 1 year if the target date falls before the birth date in that year.
DateTime birthDayPersonA = new DateTime(1986,12,1);
DateTime givenDate = new DateTime(2012,12,24);
TimeSpan age = givenDate.Substract(birthDayPersonA);
You can do the following:
Create DateTime instance with the date of birth
Create DateTime instance with the destination (e.g. 31/12/2012 23:59:59);
Use the Subtract method on the second DateTime instance to get the years between this two dates and add it to the user age
var age = new Timespan(endOfYearDate.Ticks - dateOfBirth.Ticks).TotalDays();
or just days if you want it to round for you.
NOTE you will need to convert days to years by dividing by 365.25
VB has DataDiff, C# doesn't exactly. Use the below classes
public enum DateInterval
{
Day,
DayOfYear,
Hour,
Minute,
Month,
Quarter,
Second,
Weekday,
WeekOfYear,
Year
}
public class DateAndTime
{
public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2)
{
return DateDiff(interval, dt1, dt2, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
}
private static int GetQuarter(int nMonth)
{
if (nMonth <= 3)
return 1;
if (nMonth <= 6)
return 2;
if (nMonth <= 9)
return 3;
return 4;
}
public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2, DayOfWeek eFirstDayOfWeek)
{
if (interval == DateInterval.Year)
return dt2.Year - dt1.Year;
if (interval == DateInterval.Month)
return (dt2.Month - dt1.Month) + (12 * (dt2.Year - dt1.Year));
TimeSpan ts = dt2 - dt1;
if (interval == DateInterval.Day || interval == DateInterval.DayOfYear)
return Round(ts.TotalDays);
if (interval == DateInterval.Hour)
return Round(ts.TotalHours);
if (interval == DateInterval.Minute)
return Round(ts.TotalMinutes);
if (interval == DateInterval.Second)
return Round(ts.TotalSeconds);
if (interval == DateInterval.Weekday)
{
return Round(ts.TotalDays / 7.0);
}
if (interval == DateInterval.WeekOfYear)
{
while (dt2.DayOfWeek != eFirstDayOfWeek)
dt2 = dt2.AddDays(-1);
while (dt1.DayOfWeek != eFirstDayOfWeek)
dt1 = dt1.AddDays(-1);
ts = dt2 - dt1;
return Round(ts.TotalDays / 7.0);
}
if (interval == DateInterval.Quarter)
{
double d1Quarter = GetQuarter(dt1.Month);
double d2Quarter = GetQuarter(dt2.Month);
double d1 = d2Quarter - d1Quarter;
double d2 = (4 * (dt2.Year - dt1.Year));
return Round(d1 + d2);
}
return 0;
}
private static long Round(double dVal)
{
if (dVal >= 0)
return (long)Math.Floor(dVal);
return (long)Math.Ceiling(dVal);
}
}
usage would be
public long HowOldAmIToday(DateTime DOB)
{
return DateAndTime.DateDiff(DateInterval.Year, DOB, DateTime.Today);
}
var birthday = new DateTime(1973, 7, 10);
var date = new DateTime(2012, 12, 31);
TimeSpan span = date - birthday;
DateTime age = DateTime.MinValue + span;
// MinValue is 1/1/1 so we have to subtract one year
int yearsOfAge = age.Year - 1;
This question already has answers here:
How do I calculate someone's age based on a DateTime type birthday?
(74 answers)
Closed 6 years ago.
How can I calculate date difference between two dates in years?
For example: (Datetime.Now.Today() - 11/03/2007) in years.
I have written an implementation that properly works with dates exactly one year apart.
However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.
So without further ado, here is the code:
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);
TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);
Use:
int Years(DateTime start, DateTime end)
{
return (end.Year - start.Year - 1) +
(((end.Month > start.Month) ||
((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}
We had to code a check to establish if the difference between two dates, a start and end date was greater than 2 years.
Thanks to the tips above it was done as follows:
DateTime StartDate = Convert.ToDateTime("01/01/2012");
DateTime EndDate = Convert.ToDateTime("01/01/2014");
DateTime TwoYears = StartDate.AddYears(2);
if EndDate > TwoYears .....
If you need it for knowing someone's age for trivial reasons then Timespan is OK but if you need for calculating superannuation, long term deposits or anything else for financial, scientific or legal purposes then I'm afraid Timespan won't be accurate enough because Timespan assumes that every year has the same number of days, same # of hours and same # of seconds).
In reality the length of some years will vary (for different reasons that are outside the scope of this answer). To get around Timespan's limitation then you can mimic what Excel does which is:
public int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
//Excel documentation says "COMPLETE calendar years in between dates"
int years = endDate.Year - startDate.Year;
if (startDate.Month == endDate.Month &&// if the start month and the end month are the same
endDate.Day < startDate.Day// AND the end day is less than the start day
|| endDate.Month < startDate.Month)// OR if the end month is less than the start month
{
years--;
}
return years;
}
var totalYears =
(DateTime.Today - new DateTime(2007, 03, 11)).TotalDays
/ 365.2425;
Average days from Wikipedia/Leap_year.
int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;
To calculate the elapsed years (age), the result will be minus one.
var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;
Here is a neat trick which lets the system deal with leap years automagically. It gives an accurate answer for all date combinations.
DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0);
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0);
DateTime tmp = dt1;
int years = -1;
while (tmp < dt2)
{
years++;
tmp = tmp.AddYears(1);
}
Console.WriteLine("{0}", years);
It's unclear how you want to handle fractional years, but perhaps like this:
DateTime now = DateTime.Now;
DateTime origin = new DateTime(2007, 11, 3);
int calendar_years = now.Year - origin.Year;
int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1);
int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1);
I implemented an extension method to get the number of years between two dates, rounded by whole months.
/// <summary>
/// Gets the total number of years between two dates, rounded to whole months.
/// Examples:
/// 2011-12-14, 2012-12-15 returns 1.
/// 2011-12-14, 2012-12-14 returns 1.
/// 2011-12-14, 2012-12-13 returns 0,9167.
/// </summary>
/// <param name="start">
/// Stardate of time period
/// </param>
/// <param name="end">
/// Enddate of time period
/// </param>
/// <returns>
/// Total Years between the two days
/// </returns>
public static double DifferenceTotalYears(this DateTime start, DateTime end)
{
// Get difference in total months.
int months = ((end.Year - start.Year) * 12) + (end.Month - start.Month);
// substract 1 month if end month is not completed
if (end.Day < start.Day)
{
months--;
}
double totalyears = months / 12d;
return totalyears;
}
public string GetAgeText(DateTime birthDate)
{
const double ApproxDaysPerMonth = 30.4375;
const double ApproxDaysPerYear = 365.25;
int iDays = (DateTime.Now - birthDate).Days;
int iYear = (int)(iDays / ApproxDaysPerYear);
iDays -= (int)(iYear * ApproxDaysPerYear);
int iMonths = (int)(iDays / ApproxDaysPerMonth);
iDays -= (int)(iMonths * ApproxDaysPerMonth);
return string.Format("{0} år, {1} måneder, {2} dage", iYear, iMonths, iDays);
}
I found this at TimeSpan for years, months and days:
DateTime target_dob = THE_DOB;
DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1
int yr = true_age.Year - 1;
If you're dealing with months and years you need something that knows how many days each month has and which years are leap years.
Enter the Gregorian Calendar (and other culture-specific Calendar implementations).
While Calendar doesn't provide methods to directly calculate the difference between two points in time, it does have methods such as
DateTime AddWeeks(DateTime time, int weeks)
DateTime AddMonths(DateTime time, int months)
DateTime AddYears(DateTime time, int years)
DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);
int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days
int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days
int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365
Works perfect:
internal static int GetDifferenceInYears(DateTime startDate)
{
int finalResult = 0;
const int DaysInYear = 365;
DateTime endDate = DateTime.Now;
TimeSpan timeSpan = endDate - startDate;
if (timeSpan.TotalDays > 365)
{
finalResult = (int)Math.Round((timeSpan.TotalDays / DaysInYear), MidpointRounding.ToEven);
}
return finalResult;
}
Simple solution:
public int getYearDiff(DateTime startDate, DateTime endDate){
int y = Year(endDate) - Year(startDate);
int startMonth = Month(startDate);
int endMonth = Month(endDate);
if (endMonth < startMonth)
return y - 1;
if (endMonth > startMonth)
return y;
return (Day(endDate) < Day(startDate) ? y - 1 : y);
}
This is the best code to calculate year and month difference:
DateTime firstDate = DateTime.Parse("1/31/2019");
DateTime secondDate = DateTime.Parse("2/1/2016");
int totalYears = firstDate.Year - secondDate.Year;
int totalMonths = 0;
if (firstDate.Month > secondDate.Month)
totalMonths = firstDate.Month - secondDate.Month;
else if (firstDate.Month < secondDate.Month)
{
totalYears -= 1;
int monthDifference = secondDate.Month - firstDate.Month;
totalMonths = 12 - monthDifference;
}
if ((firstDate.Day - secondDate.Day) == 30)
{
totalMonths += 1;
if (totalMonths % 12 == 0)
{
totalYears += 1;
totalMonths = 0;
}
}
Maybe this will be helpful for answering the question: Count of days in given year,
new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too
Regarding DateTime.DayOfYear Property.
The following is based off Dana's simple code which produces the correct answer in most cases. But it did not take in to account less than a year between dates. So here is the code that I use to produce consistent results:
public static int DateDiffYears(DateTime startDate, DateTime endDate)
{
var yr = endDate.Year - startDate.Year - 1 +
(endDate.Month >= startDate.Month && endDate.Day >= startDate.Day ? 1 : 0);
return yr < 0 ? 0 : yr;
}