I have created a simple age calculator. I want to remove decimal places but the problem is when I substract now
to bday
.
example : I input 2012
, 10
and 23
and the date now is 2014-10-22
,
So when 2014.1022 - 2012.1023
the result would be 1.9999...
I want to remove all decimal places and remain the whole number 1
, but the time I use String.Format("{0:00}"
It rounds off the result to 02
even when I use ConvertToInt32
, I don't want to use split string it needs a lot of code.
Any Ideas?
static void Main(string[] args)
{
string year, month, day = string.Empty;
Console.WriteLine("Enter your Birthdate:");
Console.WriteLine("Year :");
year = Console.ReadLine();
Console.WriteLine("Month :");
month = Console.ReadLine();
Console.WriteLine("Day :" );
day = Console.ReadLine();
try
{
DateTime date = Convert.ToDateTime(year + "-" + month + "-" + day);
var bday = float.Parse(date.ToString("yyyy.MMdd"));
var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd"));
if (now < bday)
{
Console.WriteLine("Invalid Input of date");
Console.ReadLine();
}
Console.WriteLine("Your Age is " + (String.Format("{0:00}", (now - bday)))); //it rounds off my float
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
Contrary to the comments, TimeSpan
does not help you here, because a year is not a fixed length of time. That in turn leads to your expressed aim being very strange indeed. You really shouldn't be representing a date as a fractional number with the first two digits being months and the third and fourth digits being days. Time just doesn't work like that. (Consider that the difference between 2014.0131 and 2014.0201 is much greater than the difference between 2014.0130 and 2014.0131, for example.)
It would be better to represent an age in terms of years, months and days. My Noda Time library makes that pretty simple:
LocalDate birthday = new LocalDate(1976, 6, 19); // For example
LocalDate today = LocalDateTime.FromDateTime(DateTime.Now).Date; // See below
Period period = Period.Between(birthday, today);
Console.WriteLine("You are {0} years, {1} months, {2} days old",
period.Years, period.Months, period.Days);
If you want to just determine a number of years, you could decide to just use period.Years
, or possibly round the result based on period.Months
as well.
I would recommend against using DateTime.Now
in production code, however. In Noda Time, we have an IClock
interface representing "a means of getting the current instant in time", with a SystemClock
implementation in the main assembly and a FakeClock
implementation in the testing assembly. Your code would accept an IClock
(possibly with dependency injection) and then use that to determine the current date in whatever time zone you're interested in. That way, you can write tests for any situation you like, without changing your computer's clock. This is a good way of handling time-related tasks in general, IMO.