Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

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.

like image 273
User Avatar asked Mar 21 '12 22:03

User


1 Answers

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.

like image 185
Jon Skeet Avatar answered Sep 18 '22 12:09

Jon Skeet