.NET Compact Framework上的DateTime.Now中的毫秒数始终为零?

Mar*_*cel 13 c# datetime timestamp compact-framework windows-mobile

我希望在Windows Mobile项目上有日志时间戳.精度必须至少在100毫秒的范围内.

但是我的调用DateTime.Now返回一个属性设置为零的DateTime对象Millisecond.该Ticks物业也相应地四舍五入.

如何获得更好的时间准确度?
请记住,我的代码在Compact Framework 3.5版上运行.我使用的是HTC touch Pro 2设备.

基于MusiGenesis的答案,我创建了以下类来解决这个问题:

/// <summary>
/// A more precisely implementation of some DateTime properties on mobile devices.
/// </summary>
/// <devdoc>Tested on a HTC Touch Pro2.</devdoc>
public static class DateTimePrecisely
{
    /// <summary>
    /// Remembers the start time when this model was created.
    /// </summary>
    private static DateTime _start = DateTime.Now;
    /// <summary>
    /// Remembers the system uptime ticks when this model was created. This
    /// serves as a more precise time provider as DateTime.Now can do.
    /// </summary>
    private static int _startTick = Environment.TickCount;

    /// <summary>
    /// Gets a DateTime object that is set exactly to the current date and time on this computer, expressed as the local time.
    /// </summary>
    /// <returns></returns>
    public static DateTime Now
    {
        get
        {
            return _start.AddMilliseconds(Environment.TickCount - _startTick);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mus*_*sis 14

Environment.TickCount 将返回自上次重新引导以来Windows(或Windows Mobile)运行的毫秒数.

要使用它,请将以下两个表单级变量添加到代码中:

private DateTime _start;
private int _startTick;
Run Code Online (Sandbox Code Playgroud)

在表单的Load事件中,执行以下操作:

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

每当您需要具有毫秒的DateTime对象时,请执行以下操作:

DateTime timeStamp = 
    _start.AddMilliseconds(Environment.TickCount - _startTick);
Run Code Online (Sandbox Code Playgroud)

Environment.TickCount是一个int和这个值将Int32.MinValue在25天左右"环绕" .如果您的设备将在没有重新启动的情况下运行那么长时间,您将需要添加一个Environment.TickCount小于上次读取值的值的检查,并重置两者_start,_startTick如果是,则重置.

  • 这是HTC的失败,而不是微软的失败.由OEM为操作系统提供时间. (3认同)