Just a few quick .NET samples for performing some common tasks that the .NET Framework doesn't do for you:
System uptime
using System.Diagnostics;
public TimeSpan GetUptime() {
PerformanceCounter systemUpTime = new PerformanceCounter("System", "System Up Time");
systemUpTime.NextValue(); // Required to work!
return TimeSpan.FromSeconds(systemUpTime.NextValue())));
}
Calculating age
public int GetAge(DateTime birthday) {
int years = DateTime.Now.Year - birthday.Year;
return (birthday.DayOfYear >= DateTime.Now.DayOfYear) ? years : years - 1;
}
Rounding to n decimal places
public decimal ArithmeticRound(decimal d, int decimals) {
decimal power = (decimal)Math.Pow(10, decimals);
return (decimal.Floor((Math.Abs(d) * power) + 0.4m) / power) * Math.Sign(d);
}
[)amien









0 responses to “.NET quick samples: Uptimes, ages, rounding to n places”
Leave a reply