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.
JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.
Find timestamp from DateTime:
At the moment you're calling
ToUniversalTime()
- just get rid of that:Alternatively, and rather more readably IMO:
EDIT: As noted in the comments, the
Kind
of theDateTime
you pass in isn't taken into account when you perform subtraction. You should really pass in a value with aKind
ofUtc
for this to work. Unfortunately,DateTime
is a bit broken in this respect - see my blog post (a rant aboutDateTime
) for more details.You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.
I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:
Since you named a variable epoch, do you want the Unix time equivalent of your date?