SetComputerDateTime.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace LYFZ.WinAPI
  6. {
  7. public class SetComputerDateTime
  8. {
  9. [DllImport("kernel32.dll", EntryPoint = "GetSystemDefaultLCID")]
  10. public static extern int GetSystemDefaultLCID();
  11. [DllImport("kernel32.dll", EntryPoint = "SetLocaleInfoA")]
  12. public static extern int SetLocaleInfo(int Locale, int LCType, string lpLCData);
  13. public const int LOCALE_SLONGDATE = 0x20;
  14. public const int LOCALE_SSHORTDATE = 0x1F;
  15. public const int LOCALE_STIME = 0x1E;
  16. [DllImportAttribute("Kernel32.dll")]
  17. public static extern void SetLocalTime(SystemTime st);
  18. //public ushort wYear;
  19. //public ushort wMonth;
  20. //public ushort wDayOfWeek;
  21. //public ushort wDay;
  22. //public ushort wHour;
  23. //public ushort wMinute;
  24. //public ushort wSecond;
  25. //public ushort wMilliseconds;
  26. public SetComputerDateTime()
  27. {
  28. }
  29. /// <summary>
  30. /// 设置系统时间格式
  31. /// </summary>
  32. public static void SetDateTimeFormat()
  33. {
  34. try
  35. {
  36. int x = GetSystemDefaultLCID();
  37. SetLocaleInfo(x, LOCALE_SSHORTDATE, "yyyy-MM-dd"); //短日期格式
  38. SetLocaleInfo(x, LOCALE_SLONGDATE, "yyyy年MM月dd日"); //长日期格式
  39. SetLocaleInfo(x, LOCALE_STIME, "HH:mm:ss"); //时间格式
  40. }
  41. catch
  42. {
  43. }
  44. }
  45. /// <summary>
  46. /// 设置系统时间
  47. /// </summary>
  48. /// <param name="dateTime"></param>
  49. public static void SetDateTime(DateTime dateTime)
  50. {
  51. try
  52. {
  53. SystemTime mySystemTime = new SystemTime();
  54. mySystemTime.wYear = (ushort)dateTime.Year;//年
  55. mySystemTime.wMonth = (ushort)dateTime.Month;//月
  56. mySystemTime.wDay = (ushort)dateTime.Day;//日
  57. mySystemTime.wHour = (ushort)dateTime.Hour;//时
  58. mySystemTime.wMinute = (ushort)dateTime.Minute;//分
  59. mySystemTime.wSecond = (ushort)dateTime.Second;//秒
  60. SetLocalTime(mySystemTime);
  61. }
  62. catch
  63. {
  64. }
  65. }
  66. }
  67. [StructLayoutAttribute(LayoutKind.Sequential)]
  68. public class SystemTime
  69. {
  70. public ushort wYear;
  71. public ushort wMonth;
  72. public ushort wDayOfWeek;
  73. public ushort wDay;
  74. public ushort wHour;
  75. public ushort wMinute;
  76. public ushort wSecond;
  77. public ushort wMilliseconds;
  78. }
  79. }