Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mktime() and microtime() equivalent in C#

Tags:

c#

What is the equivalent of PHP mktime and microtime in C#?

like image 617
Yana D. Nugraha Avatar asked Dec 10 '22 20:12

Yana D. Nugraha


2 Answers

Here's for mktime (you'll have to verify timezones, though):

static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddSeconds(timestamp);
}

static int ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    TimeSpan diff = date - origin;
    return (int)diff.TotalSeconds;
}

microtime is basically the same, but you don't have to cast to int.

like image 51
Anton Gogolev Avatar answered Dec 26 '22 11:12

Anton Gogolev


There are no direct equivalents, but they can easily be implemented... Since the UNIX timestamp is the number of seconds since January 1st 1970, it's easy to calculate :

public readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);

// equivalent to PHP mktime :
public int GetUnixTimestamp(DateTime dt)
{
    TimeSpan span = dt - UnixEpoch;
    return (int)span.TotalSeconds;
}

For microtime, you can use the DateTime.Tick property (1 tick = 100 nanoseconds, so 10 ticks = 1 microsecond)

like image 32
Thomas Levesque Avatar answered Dec 26 '22 11:12

Thomas Levesque