This is just for fun. You know how old you are(I hope), but do you know how many days you are walking around on this planet?
The two routines presented here could be used more practically in an ever present employee application.
Fun with DateTime and TimeSpan
using System;
namespace DateFun
{
class Program
{
static void Main(string[] args)
{
// Get the current date time settings from the computer
DateTime currentDay = DateTime.Now;
// Fill in a birthday
// In a form application use a DateTimePicker.
// Here normally use ReadLine, I used inits to keep it simple
int year = 1952;
int month = 1;
int day = 18;
DateTime birthDay = new DateTime(year, month, day);
Console.WriteLine("Fun with DateTime and TimeSpan!");
Console.WriteLine();
// Calculate and display an age
int yourAge = AgeCalculation(currentDay, birthDay);
Console.WriteLine("You are {0} years old (or young!).", yourAge);
// Calculate the total amount of days you are living on this planet
string daysAlive = DaysAliveCalculation(ref currentDay, ref birthDay);
Console.WriteLine("You are {0} days alive and kicking!", daysAlive);
Console.ReadKey();
}
private static string DaysAliveCalculation(ref DateTime currentDay, ref DateTime birthDay)
{
// Calculate the differnece in ticks
long DifTicks = currentDay.Ticks - birthDay.Ticks;
// Make a TimeSpan object out of it
TimeSpan TS = new TimeSpan(DifTicks);
// Extract the days out of it as a string
string daysAlive = TS.Days.ToString();
return daysAlive;
}
private static int AgeCalculation(DateTime curDate, DateTime birthDate)
{
DateTime testDate = new DateTime(curDate.Year, birthDate.Month, birthDate.Day);
int Age = curDate.Year - birthDate.Year;
// Overloaded comparision operator
if (testDate <= curDate) // You do not yet celebrate your birthday this year
{
Age--;
}
return Age;
}
}
}
subtercosm 0 Light Poster
ddanbe 2,724 Professional Procrastinator Featured Poster
anmoldeep 0 Newbie Poster
ddanbe 2,724 Professional Procrastinator Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.