I'm new to C# and have been doing an exercise from a book. The exercise is to write a program that reads my age from the console and prints my age after ten years from now.
Here is the code I have written based on what I have understood so far.
namespace Page_108_Age
{
class Program
{
static void Main(string[] args)
{
//Gives date of birth
DateTime dob = new DateTime(1989, 10, 30, 23, 31, 00);
//Gives current age
DateTime today = DateTime.Today;
int age = today.Year -dob.Year;
if (today < dob.AddYears(age)) age--;
//age plus ten years
DateTime agePlusTen = age.AddYears(10);
Console.WriteLine(age);
Console.ReadLine();
}
}
}
My problem is that AddYears in line 16
[DateTime dobPlusTen = age.AddYears(10);]
is giving me the following error...
'int' does not contain a definition for 'AddYears' and no extension
method 'AddYears' accepting a first argument of type 'int' could be
found (are you missing a using directive or an assembly reference?)
I'm obviously missing something but now sure what other then I think I need to define AddYears as it is not highlighted in my code as a struct.
Note: apologies for the "dobPlusTen" as most of you picked up on this is short for date of birth plus ten years which is not what it is supposed to be as I want Current Age Plus Ten Years, I changed it to agePlusTen.
You write:
DateTime dobPlusTen = age.AddYears(10);
Doesn't this ring your bell?
Your variable is named dobPlusTen, yet the value you assign to it is not dob + 10.
So change it to
DateTime dobPlusTen = dob.AddYears(10);
and you'll be all right.
EDIT As per Ross Dargan's remark below this answer (I had failed to notice the exact question: The exercise is to write a program that reads my age from the console and prints my age after ten years from now.), it's actually much simpler.
Just a
var line = Console.ReadLine();
int agePlus10 = Convert.ToInt32(line) + 10;
Console.WriteLine(agePlus10);
will do.
Close :-)
Age is an int, so that method doesn't exist (it exists on DateTime). This should put you on the right track:-
class Program
{
static void Main(string[] args)
{
//Gives date of birth
DateTime dob = new DateTime(1989, 10, 30, 23, 31, 00);
//Gives current age
DateTime today = DateTime.Today;
int age = today.Year -dob.Year;
if (today < dob.AddYears(age)) age--;
//age plus ten years
age = age +10;
DateTime agePlusTen = dob.AddYears(age);
Console.WriteLine(agePlusTen.ToShortDateString());
Console.ReadLine();
}
}
I guess there's a couple of ways to look at this.
First, age is an integer. So it has no AddYears method. You could just add 10 to it:
age += 10;
Or, if you want to use the AddYears method of the DateTime type, you'll need to do it using a DateTime variable. Such as
DateTime dobPlusTen = dob.AddYears(10);
I did the same exercise from Fundamentals of computer programming book.
In the solution and guide line for that question they asked to use the methods Console.ReadLine(), int.Parse() and DateTime.AddYears(), my solution sticking to those 3 methods:
Console.WriteLine("Enter Age:");
string Age = Console.ReadLine();
int ma = int.Parse(Age);
DateTime today = DateTime.Now;
// add the 10 years to today's date
DateTime future = today.AddYears(10);
// add your age to future
DateTime futurYear = future.AddYears(ma);
// now subtract them to get your age in 10 years from now
int fa = futurYear.Year - today.Year;
Console.WriteLine("\nIn 10 years you will be:");
Console.WriteLine(fa);
You should be sticking to using DateTime objects, since integers have no concepts of dates/years (as given by the error). Instead do something like:
int yearsOld = (int)(today.Subtract(dob).TotalDays / 365);
This lets you work with TimeSpan objects, so you could get the exact age and not just an approximation. You could just add 10 to this after.
EDIT:
Of course this isn't accounting for leap years, and I'm rounding down to the lower year, but perhaps you get the idea.
age is an int representing the number of years, not a DateTime. AddYears is a method that exists on DateTime, not int. You should either simply add 10 to the age, or add or subtract 10 years from a DateTime (add 10 to today or subtract 10 from dob; these are pretty much the same) to come up with the right number:
int agePlusTen = age + 10;
// or
DateTime tenYearsFromNow = today.AddYears(10);
int age = tenYearsFromNow.Year - dob.Year;
if (tenYearsFromNow < dob.AddYears(age)) age--;
My version:
Console.WriteLine("Please, enter your age");
string age = Console.ReadLine();
Console.WriteLine("\nIn 10 years you will be:");
DateTime myNewAge = new DateTime(int.Parse(age));
Console.WriteLine(int.Parse(age) + 10);
Related
I have to write a program that reads birthday date from the console (in the format MM.DD.YYYY) and prints current age and age in 10 years.
This is one of my first codes and in my opinion it looks too lame. I believe there is a better way to write this, so I would like to ask you for suggestions on how to optimize the code.
using System;
namespace Age
{
class Age
{
static void Main()
{
string birthDayAsk;
Console.WriteLine("Date format: MM.DD.YYYY");
birthDayAsk = Console.ReadLine();
DateTime birthday = DateTime.Parse(birthDayAsk);
DateTime today = DateTime.Today;
int age = today.Year - birthday.Year;
if ((birthday.Month > today.Month) || ((birthday.Month == today.Month) && (birthday.Day > today.Day)))
{
age = age - 1;
Console.WriteLine(age);
}
else
{
Console.WriteLine(age);
}
Console.WriteLine(age + 10);
}
}
}
I think its best to use TimeSpan to calculate difference between two dates Determining the Span Between Two Dates
Also to add the years do age.AddYears(10);
This question already has answers here:
How do I calculate someone's age based on a DateTime type birthday?
(74 answers)
Closed 7 years ago.
string birthDay = "";
_birthDay = DateTime.Parse(this.BirthDay.Value.ToString()).ToString("yyyyMMdd");
DateTime today = DateTime.Today;
int age = today.Year - _birthDay.Year;
if (_birthDay > today.AddYears(-age)) age--;
txtbox1.Text = age;
It seems error, How to calculate age from birth day?
int age = (DateTime.Today - _birthDay ).TotalDays;
if you want the difference in years you can refer this thread
TimeSpan span = DateTime.Today - _birthDay;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int age = (zeroTime + span).Year - 1;
If you want to calculate it very precision try below:
The most important thing is How many days left since you born.
the 2nd important things is how many years left since you born.
But...not every year is 365 days always.you have to consider the condition about leap year.
give you a clue:if your age is 25,assume every year is 365 days,so the days left is 365*25+x(1<=x<=365)..etc..
see:
Calculate age in C#
But you have to ask yourself about the necessary precision since timezones will affect this. In very rare cases there will some ambiguity. For example, If it's your birthday and you commit a crime when you're 17 in one timezone but 18 in another there's going to be an issue. If the answer is critical then you will need to provide some sort of message back to your user to explain some of the vagaries of computing age.
This question already has answers here:
What is the easiest way to subtract time in C#?
(7 answers)
Closed 8 years ago.
I have a certain time ie. 10.30 AM. The user makes entry in a table. If the user makes entry after 10.30 AM , then the number of minutes from 10.30 Am to the current time should be calculated and set to a string.
Here is what I tried uptil now:-
int hour = DateTime.Now.Hour;
int mins = DateTIme.Now.Minute
if(hour>10 && mins >30)
{
string lateBy = "You are late by:"+ //????? how do I calculate this?
}
Any help would be great
Use TimeSpan to find the difference between the 2 datetime values, and use the TotalMinutes property to get the difference in minutes.
DateTime today = DateTime.Today;
DateTime start = new DateTime(today.Year,today.Month,today.Day,10,30,00);
DateTime now = DateTime.Now;
int hour = now.Hour;
int mins = now.Minute;
TimeSpan ts = now.Subtract(start);
if(ts.TotalMinutes > 0) //Time now is after 10:30
{
string lateBy = "You are late by:"+ ts.TotalMinutes.ToString();
}
Ignoring dates and assuming it is always the same day as the 10:30 deadline day:
string lateBy = "You are late by:"+ ((hour-10)*60 + mins-30) + " minutes";
Note this only works before midnight, i.e. for the same day.
Since both are DateTime, you can make use of DateTime.Subract
DateTime a = new DateTime(2014, 06, 20, 10, 30, 00);
DateTime b = DateTime.Now;
Console.WriteLine("You are late by:"+b.Subtract(a).TotalMinutes +"minutes");
Console.ReadLine();
How can I get the age of someone given the date of birth in a C# datetime.
I want a precise age like 40.69 years old
This will calculate the exact age. The fractional part of the age is calculated relative to the number of days between the last and the next birthday, so it will handle leap years correctly.
The fractional part is linear across the year (and doesn't take into account the different lengths of the months), which seems to make most sense if you want to express a fractional age.
// birth date
DateTime birthDate = new DateTime(1968, 07, 14);
// get current date (don't call DateTime.Today repeatedly, as it changes)
DateTime today = DateTime.Today;
// get the last birthday
int years = today.Year - birthDate.Year;
DateTime last = birthDate.AddYears(years);
if (last > today) {
last = last.AddYears(-1);
years--;
}
// get the next birthday
DateTime next = last.AddYears(1);
// calculate the number of days between them
double yearDays = (next - last).Days;
// calcluate the number of days since last birthday
double days = (today - last).Days;
// calculate exaxt age
double exactAge = (double)years + (days / yearDays);
This would be an approximative calculation:
TimeSpan span = DateTime.Today.Subtract(birthDate);
Console.WriteLine( "Age: " + (span.TotalDays / 365.25).toString() );
BTW: see also this question on Stack Overflow: How do I calculate someone’s age in C#?
An approximite would be:
DateTime bd = new DateTime(1999, 1, 2);
TimeSpan age = DateTime.Now.Subtract(bd);
Console.WriteLine(age.TotalDays / 365.25);
The 40 years part is easy enough. But to get a truly accurate decimal point, I'm not sure how you translate the rest of the age into a decimal number. You see age is expressed in Years, Months, Days, Hours, Seconds. And the calculation isn't that easy. You have to deal with anniversary dates. Like if someone was born on January 31st, when are they 1 month old? The answer is March 1st. But in some years that is 28 days later and some years 29 days later. Here is a javascript implementation I did that tries to deal with this.
But I suppose the decimal could express the number of days since the most recent birthday anniversay divided by the number of days till the next birthday anniversary. And if you wanted to get more precise you could do it in seconds using the same principle.
But I think it is a poor representation of an age. We just don't usually represent an age like that.
And make sure your datetimes are in the same timezone for your comparisons.
You could do this:
Console.WriteLine(DateTime.Now.Date.Subtract(new DateTime(1980, 8, 1)).TotalDays / 365.25);
how much error is allowed in the fractional portion? a precise age would be
31 years, 10 days, 3 hours, etc. depending on the precision wanted.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I calculate someone's age in C#?
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age?
Maybe
DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;
The result of year is 32.77405678074
Could this code be OK?
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age?
My guess would be that this is a localization issue, though I don't know how it would happen, since (at least for me) the profile has you fill out your age in the format "YYYY/MM/DD". But your birthday is one that reads as a valid date (January 12th) in traditional U.S. settings, so this is the area I'd look into. I was born in 1975, also, and my birthday is next month, and it's got my age right.
If you were born on January 12th 1975, you would be 33 years old today.
If you were born on December 1st 1975, you would be 32 years old today.
If you read the note by the birthday field when editing your profile you'll see it says "YYYY/MM/DD", I'm sure it will try to interpret dates of other formats but it looks like it interprets MM/DD/YYYY (US standard dates) in preference to DD/MM/YYYY (European standard dates). The easy fix is to enter the date of your birthday according to the suggested input style.
Actually, because of leap years, your code would be off. Since the timespan object has no TotalYears property the best way to get it would be this
Pardon the VB.Net
Dim myAge AS Integer = DateTime.Now.year - BirthDate.year
If Birthdate.month < DateTime.Now.Month _
OrElse BirthDate.Month = DateTime.Now.Month AndAlso Birthdate.Day < DateTime.Now.Day Then
MyAge -= 1
END IF
int ag1;
string st, ag;
void agecal()
{
st = TextBox4.Text;
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.ShortDatePattern = "MM/dd/yyyy";
dtfi.DateSeparator = "/";
DateTime dt = Convert.ToDateTime(st, dtfi);
ag1 = int.Parse(dt.Year.ToString());
int years = DateTime.Now.Year - ag1;
ag = years.ToString();
TextBox3.Text = ag.ToString();
}