Function that creates a timestamp in c#

前端 未结 6 422
小蘑菇
小蘑菇 2020-11-30 19:25

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 Date

相关标签:
6条回答
  • 2020-11-30 19:41

    You can also use

    Stopwatch.GetTimestamp().ToString();

    0 讨论(0)
  • 2020-11-30 19:43

    when you need in a timestamp in seconds, you can use the following:

    var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
    
    0 讨论(0)
  • 2020-11-30 19:50

    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

    0 讨论(0)
  • 2020-11-30 20:03

    I believe you can create a unix style datestamp accurate to a second using the following

    //Find unix timestamp (seconds since 01/01/1970)
    long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
    ticks /= 10000000; //Convert windows ticks to seconds
    timestamp = ticks.ToString();
    

    Adjusting the denominator allows you to choose your level of precision

    0 讨论(0)
  • 2020-11-30 20:04

    You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)

    0 讨论(0)
  • 2020-11-30 20:04

    If you want timestamps that correspond to actual real times BUT also want them to be unique (for a given application instance), you can use the following code:

    public class HiResDateTime
    {
       private static long lastTimeStamp = DateTime.UtcNow.Ticks;
       public static long UtcNowTicks
       {
           get
           {
               long orig, newval;
               do
               {
                   orig = lastTimeStamp;
                   long now = DateTime.UtcNow.Ticks;
                   newval = Math.Max(now, orig + 1);
               } while (Interlocked.CompareExchange
                            (ref lastTimeStamp, newval, orig) != orig);
    
               return newval;
           }
       }
    }
    
    0 讨论(0)
提交回复
热议问题