Function that creates a timestamp in c#

Konstantinos picture Konstantinos · May 21, 2009 · Viewed 267.2k times · Source

I was wondering, is there a way to create a timestamp in c# from a datetime? I need a millisecond precision value that also works in Compact Framework(saying that since DateTime.ToBinary() does not exist in CF).

My problem is that i want to store this value in a database agnostic way so i can sortby it later and find out which value is greater from another etc.

Answer

RobV picture RobV · May 21, 2009

I always use something like the following:

public static String GetTimestamp(this DateTime value)
{
    return value.ToString("yyyyMMddHHmmssfff");
}

This will give you a string like 200905211035131468, as the string goes from highest order bits of the timestamp to lowest order simple string sorting in your SQL queries can be used to order by date if you're sticking values in a database