using System;
namespace Org.BouncyCastle.Utilities.Date
{
public class DateTimeUtilities
{
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
private DateTimeUtilities()
{
}
///
/// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
///
/// A UTC DateTime value not before epoch.
/// Number of whole milliseconds after epoch.
/// 'dateTime' is before epoch.
public static long DateTimeToUnixMs(
DateTime dateTime)
{
if (dateTime.CompareTo(UnixEpoch) < 0)
throw new ArgumentException("DateTime value may not be before the epoch", "dateTime");
return (dateTime.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond;
}
///
/// Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
///
/// Number of milliseconds since the epoch.
/// A UTC DateTime value
public static DateTime UnixMsToDateTime(
long unixMs)
{
return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks);
}
///
/// Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
///
public static long CurrentUnixMs()
{
return DateTimeToUnixMs(DateTime.UtcNow);
}
}
}