using System;
using LoreSoft.MathExpressions.Metadata;
namespace LoreSoft.MathExpressions.UnitConversion
{
/// Units for Time
public enum TimeUnit
{
/// Millisecond unit (ms)
[Abbreviation("ms")]
Millisecond = 0,
/// Second unit (sec)
[Abbreviation("sec")]
Second = 1,
/// Minute unit (min)
[Abbreviation("min")]
Minute = 2,
/// Hour unit (hr)
[Abbreviation("hr")]
Hour = 3,
/// Day unit (d)
[Abbreviation("d")]
Day = 4,
/// Week unit (wk)
[Abbreviation("wk")]
Week = 5
}
///
/// Class representing time convertion.
///
public static class TimeConverter
{
///
/// Converts the specified from unit to the specified unit.
///
/// Covert from unit.
/// Covert to unit.
/// Covert from value.
/// The converted value.
public static double Convert(
TimeUnit fromUnit,
TimeUnit toUnit,
double fromValue)
{
if (fromUnit == toUnit)
return fromValue;
TimeSpan span;
switch (fromUnit)
{
case TimeUnit.Millisecond:
span = TimeSpan.FromMilliseconds(fromValue);
break;
case TimeUnit.Second:
span = TimeSpan.FromSeconds(fromValue);
break;
case TimeUnit.Minute:
span = TimeSpan.FromMinutes(fromValue);
break;
case TimeUnit.Hour:
span = TimeSpan.FromHours(fromValue);
break;
case TimeUnit.Day:
span = TimeSpan.FromDays(fromValue);
break;
case TimeUnit.Week:
span = TimeSpan.FromDays(fromValue * 7d);
break;
default:
throw new ArgumentOutOfRangeException("fromUnit");
}
switch (toUnit)
{
case TimeUnit.Millisecond:
return span.TotalMilliseconds;
case TimeUnit.Second:
return span.TotalSeconds;
case TimeUnit.Minute:
return span.TotalMinutes;
case TimeUnit.Hour:
return span.TotalHours;
case TimeUnit.Day:
return span.TotalDays;
case TimeUnit.Week:
return span.TotalDays / 7d;
default:
throw new ArgumentOutOfRangeException("toUnit");
}
}
}
}