Milliseconds in DateTime.Now on .NET Compact Framework always zero?

前端 未结 4 1987
情话喂你
情话喂你 2021-02-19 11:28

i want to have a time stamp for logs on a Windows Mobile project. The accuracy must be in the range a hundred milliseconds at least.

Ho

4条回答
  •  广开言路
    2021-02-19 11:56

    Environment.TickCount will return the number of milliseconds that Windows (or Windows Mobile) has been running since the last reboot.

    To use this, add these two form-level variables to your code:

    private DateTime _start;
    private int _startTick;
    

    In your form's Load event, do this:

    private void Form1_Load(object sender, EventArgs e)
    {
        _start = DateTime.Now;
        _startTick = Environment.TickCount;
    }
    

    Whenever you need a DateTime object with milliseconds, do this:

    DateTime timeStamp = 
        _start.AddMilliseconds(Environment.TickCount - _startTick);
    

    Environment.TickCount is an int and this value will "wrap around" to Int32.MinValue after 25 days or so. If your device is going to be running that long without restarting, you'll want to add a check for an Environment.TickCount value that is less than the last value read, and reset both _start and _startTick if so.

提交回复
热议问题