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

标签 c# datetime windows-mobile compact-framework timestamp

我想为 Windows Mobile 项目 的日志添加一个时间戳。精度必须至少在一百毫秒的范围内。

但是,我对 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);
        }
    }
}

最佳答案

Environment.TickCount 将返回 Windows(或 Windows Mobile)自上次重新启动后运行的毫秒数。

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

private DateTime _start;
private int _startTick;

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

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

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

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

Environment.TickCount 是一个 int,这个值将在 25 天左右后“环绕”到 Int32.MinValue。如果您的设备将在不重启的情况下运行那么长时间,您需要添加一个检查 Environment.TickCount 值是否小于上次读取的值,并重置两个 _start _startTick 如果是的话。

关于c# - .NET Compact Framework 上 DateTime.Now 中的毫秒数始终为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2606298/

相关文章:

c# - Windows 窗体中的单点登录

scala - Spark : Parse a Date/Timestamps with different Formats (MM-dd-yyyy HH:mm, MM/dd/yy H:mm ) 在 Dataframe 的同一列

c# - Windows Mobile - 2 路通话录音 (C#)

c++ - 如何重新定位/调整屏幕上的资源?

iphone - 支持所有移动平台和 .net Web 应用程序的聊天功能框架

c# - Process.Start() 继续运行我的 .exe 作为后台进程 MVC ASP.Net

c# - 移位位移返回错误结果

python - 如何将日期时间对象四舍五入到最近的前一刻钟?

c# - 从父类ctor调用重写的方法

python - 以毫秒为单位的纪元时间转换为日期时间