1.无网络
页面部分
<DockPanel Grid.Column="1" Margin="60,82,0,0" VerticalAlignment="Top" > <DockPanel DockPanel.Dock="Top">
<TextBlock Text="日期:" VerticalAlignment="Center" />
<DatePicker x:Name="dpDate" Margin="50,0" />
</DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,30">
<TextBlock Text="时:" VerticalAlignment="Center" />
<ComboBox x:Name="cbxHour" ItemsSource="{Binding HourList}" Width="350" Margin="8,0,30,0" />
<TextBlock Text="分:" VerticalAlignment="Center" />
<ComboBox x:Name="cbxMinute" ItemsSource="{Binding TimeList}" Width="350" Margin="8,0,30,0" />
<TextBlock Text="秒:" VerticalAlignment="Center" />
<ComboBox x:Name="cbxSecond" ItemsSource="{Binding TimeList}" Width="350" Margin="8,0,30,0" />
</DockPanel>
<Button x:Name="btnChangeTime" HorizontalAlignment="Right" Content="更改时间" />
</DockPanel>
xmal.cs
Viewmodel vm{get;set;}=new Viewmodel();
public XXX()
{
this.DataContext=vm;
/// <summary>
/// 更改时间
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnChangeTime_Click(object sender, RoutedEventArgs e)
{
try
{
this.Dispatcher.Invoke(() =>
{
string dt = null;
if (dpDate.SelectedDate != null) {
dt = dpDate.SelectedDate.Value.ToString("yyyy-MM-dd"); } else { Util.ShowMsg("请选择日期"); return; }
if (cbxHour.SelectedValue != null) {
dt += " " + cbxHour.SelectedValue.ToString(); }
else { dt += " 0"; }
if (cbxMinute.SelectedValue != null)
{ dt += ":" + cbxMinute.SelectedValue.ToString(); }
else { dt += ":0"; }
if (cbxSecond.SelectedValue != null) {
dt += ":" + cbxSecond.SelectedValue.ToString(); }
else { dt += ":0"; }
if (UpdateTimeHelper.SetDate(DateTime.Parse(dt)))
{ Util.ShowMsg("设置成功"); }
}); }
catch (Exception ex) { LogUtil.LogError(ex); } }
}
viewmodel
public ObservableCollection<string> HourList { get; set; } = new ObservableCollection<string>(); public ObservableCollection<string> TimeList { get; set; } = new ObservableCollection<string>();
public Viewmodel(){
HourList.Clear();
TimeList.Clear();
for (int i = 0; i < 24; i++) { HourList.Add(i.ToString()); }
for (int i = 0; i < 60; i++) { TimeList.Add(i.ToString()); }
}
2.有网络
if (UpdateTimeHelper.SetDate())
{
Util.ShowMsg("设置成功");
}
UpdateTimeHelper.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
internal class UpdateTimeHelper
{
//设置系统时间的API函数
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME time);
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEMTIME
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
/// <summary>
/// 获取标准北京时间,读取http://www.beijing-time.org/time.asp
/// </summary>
/// <returns>返回网络时间</returns>
public static DateTime GetBeijingTime()
{
// NTP服务器地址
string ntpServer = "ntp.ntsc.ac.cn";
// 创建UDP套接字
UdpClient udpClient = new UdpClient(ntpServer, 123);
// 发送NTP请求包
byte[] ntpData = new byte[48];
ntpData[0] = 0x1B;
udpClient.Send(ntpData, ntpData.Length);
// 接收NTP响应包
IPEndPoint remoteEP = null;
byte[] responseData = udpClient.Receive(ref remoteEP);
// 关闭UDP套接字
udpClient.Close();
// 解析NTP响应包中的时间戳
ulong intPart = (ulong)responseData[40] << 24 | (ulong)responseData[41] << 16 | (ulong)responseData[42] << 8 | responseData[43];
ulong fractPart = (ulong)responseData[44] << 24 | (ulong)responseData[45] << 16 | (ulong)responseData[46] << 8 | responseData[47];
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
// 计算北京时间
DateTime ntpTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)milliseconds);
DateTime beijingTime = TimeZoneInfo.ConvertTimeFromUtc(ntpTime, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));
return beijingTime;
}
/// <summary>
/// 设置系统时间
/// </summary>
/// <param name="dt">需要设置的时间</param>
/// <returns>返回系统时间设置状态,true为成功,false为失败</returns>
public static bool SetDate()
{
SYSTEMTIME st;
DateTime dt = GetBeijingTime();
st.year = (short)dt.Year;
st.month = (short)dt.Month;
st.dayOfWeek = (short)dt.DayOfWeek;
st.day = (short)dt.Day;
st.hour = (short)dt.Hour;
st.minute = (short)dt.Minute;
st.second = (short)dt.Second;
st.milliseconds = (short)dt.Millisecond;
bool rt = SetLocalTime(ref st);
return rt;
}
public static bool SetDate(DateTime dt)
{
SYSTEMTIME st;
st.year = (short)dt.Year;
st.month = (short)dt.Month;
st.dayOfWeek = (short)dt.DayOfWeek;
st.day = (short)dt.Day;
st.hour = (short)dt.Hour;
st.minute = (short)dt.Minute;
st.second = (short)dt.Second;
st.milliseconds = (short)dt.Millisecond;
bool rt = SetLocalTime(ref st);
return rt;
}
}