日期類控制項的應用–修改系統日期時間

來源:互聯網
上載者:User

平時我們使用  System.DateTime.Now.ToString() 即可獲得系統日期時間,

但如何修改系統日期和時間呢,首先我們需要引用一個命名空間 using System.Runtime.InteropServices;

然後定義一個LibWrapDateTime類,引用API函數,代碼如下:

 

代碼

1         public class LibWrapDateTime
2 {
3 [DllImportAttribute("Kernel32.dll")]
4 public static extern void GetLocalTime(SystemTime st); //得到當前系統時間方法
5   [DllImportAttribute("Kernel32.dll")]
6 public static extern void SetLocalTime(SystemTime st); //設定系統目前時間
7   }

 


通過類是實現公開變數:

 

代碼

 1  [StructLayoutAttribute(LayoutKind.Sequential)]
2 public class SystemTime
3 {
4 public ushort wYear;
5 public ushort wMonth;
6 public ushort wDateOfWeek;
7 public ushort wDate;
8 public ushort wHour;
9 public ushort wMinute;
10 public ushort wSecond;
11 public ushort wMilliseconds;
12 }

 

 

 


下面我使用了DateTimePicker控制項設定時間:


 

代碼

 1 private void button2_Click(object sender, EventArgs e)          //設定系統目前時間
2   {
3 if (MessageBox.Show("確定修改當前日期時間?", "訊息提示", MessageBoxButtons.OK) == DialogResult.OK)
4 {
5 //DateTime year = this.dateTimePicker1.Value;
6   SystemTime MySystemTime = new SystemTime();
7 LibWrapDateTime.GetLocalTime(MySystemTime);
8 MySystemTime.wYear = (ushort)this.dateTimePicker1.Value.Year;
9 MySystemTime.wMonth = (ushort)this.dateTimePicker1.Value.Month;
10 MySystemTime.wDate = (ushort)this.dateTimePicker1.Value.Day;
11 MySystemTime.wHour = (ushort)this.dateTimePicker1.Value.Hour;
12 MySystemTime.wMinute=(ushort)this.dateTimePicker2.Value.Minute;
13 MySystemTime.wSecond = (ushort)this.dateTimePicker2.Value.Second;
14 LibWrapDateTime.SetLocalTime(MySystemTime);
15 button1_Click(null, null);
16 }
17 }

 

 代碼下載:/Files/long-gengyun/DateTime.rar 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.