Get UNIX Time Stamp using .NET

Sometimes we could need to get the UNIX time stamp, as you may know, that number is the amount of seconds since 1-1-1970 until now.

You can get this number using javascript this way:

   1: //Dialog the UNIX time stamp
   2: alert( (new Date()).getTime() );

If you want to get the same number using .NET framework, you can do something like:

   1: TimeSpan t = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime());

We’re simply subtracting dates, Now – 1/1/1970

Then, we can get the totalSeconds:

   1: int timestamp = (int)t.TotalSeconds;

But wait!, if you render this now.

   1: System.Diagnostics.Debug.Write(timestamp);

You´ll maybe obtain a floating point number, this is because DateTime.Now is a very precise object, but maybe we will not need that, so, we can do it like this:

   1: DateTime n = DateTime.Now;
   2: DateTime now = new DateTime(n.Year , n.Month , n.Day , n.Hour , n.Minute, n.Second );
   3: TimeSpan t = (now - new DateTime(1970, 1, 1).ToLocalTime());
   4: int timestamp = (int)t.TotalSeconds;

Do some test, and do it in the way it fit your needs.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: