22. 7. 7.

C# 내 로컬 PC시간 NAVER 서버 시간으로 변경

using System;
using System.Globalization;
using System.Net;
using System.Runtime.InteropServices;

namespace timechange
{
    internal class Program
    {
        [StructLayout(LayoutKind.Sequential)]
        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;
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool SetSystemTime(ref SYSTEMTIME st);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool SetLocalTime(ref SYSTEMTIME st);

        static void Main(string[] args)
        {
            DateTime dateTime = DateTime.MinValue;
            try
            {
                // 네이버 사이트 시간하고 맞춰서 시간 설정
                using (var response = WebRequest.Create("https://www.naver.com").GetResponse())
                    dateTime = DateTime.ParseExact(response.Headers["date"],
                        "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                        CultureInfo.InvariantCulture.DateTimeFormat,
                        DateTimeStyles.AssumeUniversal);
            }
            catch (Exception)
            {
                dateTime = DateTime.Now;
            }
            Console.WriteLine(dateTime);

           
            SYSTEMTIME st = new SYSTEMTIME();
            st.wYear = (short)dateTime.Year;
            st.wMonth = (short)dateTime.Month;
            st.wDay = (short)dateTime.Day;
            st.wHour = (short)dateTime.Hour;
            st.wMinute = (short)dateTime.Minute;
            st.wSecond = (short)dateTime.Second;
            st.wMilliseconds = (short)dateTime.Millisecond;

            SetSystemTime(ref st);
            SetLocalTime(ref st);
            Console.ReadKey();
        }
    }
}

댓글 없음:

댓글 쓰기