65.9K
CodeProject is changing. Read more.
Home

UNIX timestamp to System.DateTime

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.15/5 (18 votes)

Apr 11, 2005

viewsIcon

226044

downloadIcon

2

Converting UNIX timestamp to System.DateTime.

Introduction

This article is a very simple example of how to convert a UNIX timestamp to a System.DateTime in Visual C#.

The UNIX timestamp

The UNIX timestamp represents the time measured in number of seconds since the Unix Epoch (1st of January 1970 00:00:00 GMT), and is well-known to PHP-developers.

How to convert UNIX timestamp to System.DateTime

Given below is an example of how to convert any given UNIX timestamp to a System.DateTime.

// This is an example of a UNIX timestamp for the date/time 11-04-2005 09:25.
double timestamp = 1113211532;

// First make a System.DateTime equivalent to the UNIX Epoch.
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

// Add the number of seconds in UNIX timestamp to be converted.
dateTime = dateTime.AddSeconds(timestamp);

// The dateTime now contains the right date/time so to format the string,
// use the standard formatting methods of the DateTime object.
string printDate = dateTime.ToShortDateString() +" "+ dateTime.ToShortTimeString();

// Print the date and time
System.Console.WriteLine(printDate);

How to convert System.DateTime to UNIX timestamp

I know that this part is just as essential as the above, but it seems that I am running out of time... I will of course return with an update on how to convert the System.DateTime to a UNIX timestamp.

Any comments or suggestions are welcomed!

This is my first article on Visual C# ever, so bare with me...