summary refs log tree commit diff
path: root/crypto/src/util/date/DateTimeUtilities.cs
blob: 3660e29c28ed44e0e23677a1403375554d7da358 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;

namespace Org.BouncyCastle.Utilities.Date
{
	public static class DateTimeUtilities
	{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public static readonly DateTime UnixEpoch = DateTime.UnixEpoch;
#else
        public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
#endif

        public static readonly long MaxUnixMs =
            (DateTime.MaxValue.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond;
        public static readonly long MinUnixMs = 0L;

        /// <summary>
        /// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
        /// </summary>
        /// <remarks>The DateTime value will be converted to UTC (using <see cref="DateTime.ToUniversalTime"/> before
        /// conversion.</remarks>
        /// <param name="dateTime">A DateTime value not before the epoch.</param>
        /// <returns>Number of whole milliseconds after epoch.</returns>
        /// <exception cref="ArgumentOutOfRangeException">'dateTime' is before the epoch.</exception>
        public static long DateTimeToUnixMs(DateTime dateTime)
		{
            DateTime utc = dateTime.ToUniversalTime();
            if (utc.CompareTo(UnixEpoch) < 0)
				throw new ArgumentOutOfRangeException(nameof(dateTime), "DateTime value may not be before the epoch");

			return (utc.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond;
		}

        /// <summary>
        /// Create a UTC DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
        /// </summary>
        /// <param name="unixMs">Number of milliseconds since the epoch.</param>
        /// <returns>A UTC DateTime value</returns>
        /// <exception cref="ArgumentOutOfRangeException">'unixMs' is before 'MinUnixMs' or after 'MaxUnixMs'.
        /// </exception>
        public static DateTime UnixMsToDateTime(long unixMs)
		{
			if (unixMs < MinUnixMs || unixMs > MaxUnixMs)
				throw new ArgumentOutOfRangeException(nameof(unixMs));

            return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks, DateTimeKind.Utc);
		}

		/// <summary>
		/// Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
		/// </summary>
		public static long CurrentUnixMs()
		{
			return DateTimeToUnixMs(DateTime.UtcNow);
		}
	}
}