C# convert dates to Timestamp

10,667

Solution 1

Yep I think Anthony Chu is correct. I used the following site to check:

http://www.unixtimestamp.com/index.php

And it gave the answer 1405641600.

I also did the following C# to get the same answer for your example date:

var baseDate = new DateTime (1970, 01, 01);
var toDate = new DateTime (2014, 07, 18);
var numberOfSeconds = toDate.Subtract (baseDate).TotalSeconds;

Solution 2

Usually i use this extension:

public static class Extensions
{
     public static  double ToUnixTime(this DateTime input)
     {
         return input.Subtract(new DateTime(1970,1,1)).TotalSeconds;
     }
}

As you mention in question, you need PHP like TimeStamp, so you will need to round TotalSeconds(it's double right now):

public static class Extensions
{
     public static int ToUnixTime(this DateTime input)
     {
         return (int)input.Subtract(new DateTime(1970,1,1)).TotalSeconds;
     }
}
Share:
10,667
jeet
Author by

jeet

Updated on June 04, 2022

Comments

  • jeet
    jeet almost 2 years

    I got a date in the below format: 2014-07-18

    I need the unixTimeStamp of this date like PHP gives. I want to store those in a msAccess table which I can later sort on this timestamp value.

    PHP returns this timestamp for the above date: 1405641600

    How can I do this?

    Thanks