What is the equivalent of PHP mktime and microtime in C#?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With