How do I convert datetime to timestamp using C# .NET (ignoring the current timezone)?
I am using the below code:
private long ConvertToTimestamp(DateTime value) { long epoch = (value.ToUniversalTime().Ticks - 621355968000000000) / 10000000; return epoch; }
But it returns the timestamp value according to the current time zone & and I need the result without using the current timezone.
At the moment you're calling ToUniversalTime()
- just get rid of that:
private long ConvertToTimestamp(DateTime value) { long epoch = (value.Ticks - 621355968000000000) / 10000000; return epoch; }
Alternatively, and rather more readably IMO:
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); ... private static long ConvertToTimestamp(DateTime value) { TimeSpan elapsedTime = value - Epoch; return (long) elapsedTime.TotalSeconds; }
EDIT: As noted in the comments, the Kind
of the DateTime
you pass in isn't taken into account when you perform subtraction. You should really pass in a value with a Kind
of Utc
for this to work. Unfortunately, DateTime
is a bit broken in this respect - see my blog post (a rant about DateTime
) for more details.
You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With