.NET quick samples: Up-times, ages, rounding to n places
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() {
var systemUpTime = new PerformanceCounter("System", "System Up Time");
systemUpTime.NextValue(); // Required to work!
return TimeSpan.FromSeconds(systemUpTime.NextValue())));
}
Calculating age
public int GetAge(DateTime birthday) {
return DateTime.Now.Year - birthday.Year -
(((DateTime.Now.Month < birthday.Month) ||
(DateTime.Now.Month == birthday.Month &&
DateTime.Now.Day < birthday.Day)) ? 1 : 0);
}
Rounding to n decimal places
public decimal ArithmeticRound(decimal d, int decimals) {
var 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: Up-times, ages, rounding to n places