This code will allow you to generate a unix timestamp for a given DateTime, turn a unix timestamp back into a DateTime, or get the current unix timestamp.
64-bit version (future proof)
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XeonProductions { static class UnixTimestamp { public static DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0); public static ulong DateTimeToUnixTimestamp(DateTime time) { return (ulong)(time - UnixEpoch).TotalSeconds; } public static DateTime UnixTimestampToDateTime(ulong timestamp) { return UnixEpoch.AddSeconds(timestamp); } public static ulong Now { get { return (ulong)(DateTime.UtcNow - UnixEpoch).TotalSeconds; } } } } |
32-bit signed version
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XeonProductions { static class UnixTimestamp { public static DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0); public static int DateTimeToUnixTimestamp(DateTime time) { return (int)(time - UnixEpoch).TotalSeconds; } public static DateTime UnixTimestampToDateTime(int timestamp) { return UnixEpoch.AddSeconds(timestamp); } public static int Now { get { return (int)(DateTime.UtcNow - UnixEpoch).TotalSeconds; } } } } |