WinCE 同步时间

最近项目中PDA的时间总是与业务数据时间不符,因此需要一个这样的功能。

首先确定使用WebService的Response信息作为时间的获取源头。

代码如下

#region 修改系统日期
[DllImport("coredll.dll")]
private static extern bool SetLocalTime(ref SystemTime lpSystemTime);

public struct SystemTime
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}

/// <summary>
/// 设置系统当前日期
/// </summary>
public static void SetTime()
{

    WebRequest request = null;
    WebResponse response = null;
    WebHeaderCollection headerCollection = null;

    string webserviceUrl = string.Format("http://{0}/axis/servlet/AxisServlet", DB.GetServerAddr());
    string datetime = string.Empty;
    CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
    // Tue, 11 Sep 2018 09:46:58 GMT
    string format = "r";

    try
    {
        request = WebRequest.Create(webserviceUrl);
        request.Timeout = -1;
        request.Credentials = CredentialCache.DefaultCredentials;
        response = request.GetResponse();
        headerCollection = response.Headers;
        foreach (var item in headerCollection.AllKeys)
        {
            if (item.Equals("Date",StringComparison.CurrentCultureIgnoreCase))
            {
                datetime = headerCollection[item];
            }
        }

        SystemTime newTime = new SystemTime();
        DateTime dt = DateTime.ParseExact(datetime, format, cultureInfo).AddHours(8.00);

        newTime.wYear = Convert.ToInt16(dt.Year);
        newTime.wMonth = Convert.ToInt16(dt.Month);
        newTime.wDay = Convert.ToInt16(dt.Day);
        newTime.wDayOfWeek = Convert.ToInt16(dt.DayOfWeek);
        newTime.wHour = Convert.ToInt16(dt.Hour);
        newTime.wMinute = Convert.ToInt16(dt.Minute);
        newTime.wSecond = Convert.ToInt16(dt.Second);

        SetLocalTime(ref newTime);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (request != null)
        {
            request.Abort();
        }
        if (response != null)
        {
            response.Close();
        }
        if (headerCollection != null)
        {
            headerCollection.Clear();
        }
    }
}
#endregion

There are no comment yet.

HTML tag cannot be used in this comment.