• C#获取时间


    获取Internet服务器的时间

    using System;
    using System.Net;
    using System.Net.Sockets;
    
    namespace SNTPTime
    {
        // Leap indicator field values
        public enum _LeapIndicator
        {
            NoWarning,  // 0 - No warning
            LastMinute61, // 1 - Last minute has 61 seconds
            LastMinute59, // 2 - Last minute has 59 seconds
            Alarm   // 3 - Alarm condition (clock not synchronized)
        }
    
        //Mode field values
        public enum _Mode
        {
            SymmetricActive, // 1 - Symmetric active
            SymmetricPassive, // 2 - Symmetric pasive
            Client,    // 3 - Client
            Server,    // 4 - Server
            Broadcast,   // 5 - Broadcast
            Unknown    // 0, 6, 7 - Reserved
        }
    
        // Stratum field values
        public enum _Stratum
        {
            Unspecified,   // 0 - unspecified or unavailable
            PrimaryReference,  // 1 - primary reference (e.g. radio-clock)
            SecondaryReference,  // 2-15 - secondary reference (via NTP or SNTP)
            Reserved    // 16-255 - reserved
        }
    
            /// 
        /// Initialize - Sets up data structure and prepares for connection.
        /// 
        /// Connect - Connects to the time server and populates the data structure.
        /// 
        /// IsResponseValid - Returns true if received data is valid and if comes from
        /// a NTP-compliant time server.
        /// 
        /// ToString - Returns a string representation of the object.
        /// 
        /// -----------------------------------------------------------------------------
        /// Structure of the standard NTP header (as described in RFC 2030)
        ///                       1                   2                   3
        ///   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |LI | VN  |Mode |    Stratum    |     Poll      |   Precision   |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                          Root Delay                           |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                       Root Dispersion                         |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                     Reference Identifier                      |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                                                               |
        ///  |                   Reference Timestamp (64)                    |
        ///  |                                                               |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                                                               |
        ///  |                   Originate Timestamp (64)                    |
        ///  |                                                               |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                                                               |
        ///  |                    Receive Timestamp (64)                     |
        ///  |                                                               |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                                                               |
        ///  |                    Transmit Timestamp (64)                    |
        ///  |                                                               |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                 Key Identifier (optional) (32)                |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        ///  |                                                               |
        ///  |                                                               |
        ///  |                 Message Digest (optional) (128)               |
        ///  |                                                               |
        ///  |                                                               |
        ///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        /// 
        /// -----------------------------------------------------------------------------
        /// 
        /// NTP Timestamp Format (as described in RFC 2030)
        ///                         1                   2                   3
        ///     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        /// |                           Seconds                             |
        /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        /// |                  Seconds Fraction (0-padded)                  |
        /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        /// 
        /// </summary>
        public class SNTPTimeClient
        {
            // NTP Data Structure Length
            private const byte NTPDataLength = 48;
            // NTP Data Structure (as described in RFC 2030)
            byte[] NTPData = new byte[NTPDataLength];
    
            // Offset constants for timestamps in the data structure
            private const byte offReferenceID = 12;
            private const byte offReferenceTimestamp = 16;
            private const byte offOriginateTimestamp = 24;
            private const byte offReceiveTimestamp = 32;
            private const byte offTransmitTimestamp = 40;
    
            // Leap Indicator
            public _LeapIndicator LeapIndicator
            {
                get
                {
                    // Isolate the two most significant bits
                    byte val = (byte)(NTPData[0] >> 6);
                    switch (val)
                    {
                        case 0: return _LeapIndicator.NoWarning;
                        case 1: return _LeapIndicator.LastMinute61;
                        case 2: return _LeapIndicator.LastMinute59;
                        case 3:
                        default:
                            return _LeapIndicator.Alarm;
                    }
                }
            }
    
            // Version Number
            public byte VersionNumber
            {
                get
                {
                    // Isolate bits 3 - 5
                    byte val = (byte)((NTPData[0] & 0x38) >> 3);
                    return val;
                }
            }
    
            // Mode
            public _Mode Mode
            {
                get
                {
                    // Isolate bits 0 - 3
                    byte val = (byte)(NTPData[0] & 0x7);
                    switch (val)
                    {
                        case 0:
                        case 6:
                        case 7:
                        default:
                            return _Mode.Unknown;
                        case 1:
                            return _Mode.SymmetricActive;
                        case 2:
                            return _Mode.SymmetricPassive;
                        case 3:
                            return _Mode.Client;
                        case 4:
                            return _Mode.Server;
                        case 5:
                            return _Mode.Broadcast;
                    }
                }
            }
    
            // Stratum
            public _Stratum Stratum
            {
                get
                {
                    byte val = (byte)NTPData[1];
                    if (val == 0) return _Stratum.Unspecified;
                    else
                        if (val == 1) return _Stratum.PrimaryReference;
                        else
                            if (val <= 15) return _Stratum.SecondaryReference;
                            else
                                return _Stratum.Reserved;
                }
            }
    
            // Poll Interval
            public uint PollInterval
            {
                get
                {
                    return (uint)Math.Round(Math.Pow(2, NTPData[2]));
                }
            }
    
            // Precision (in milliseconds)
            public double Precision
            {
                get
                {
                    return (1000 * Math.Pow(2, NTPData[3]));
                }
            }
    
            // Root Delay (in milliseconds)
            public double RootDelay
            {
                get
                {
                    int temp = 0;
                    temp = 256 * (256 * (256 * NTPData[4] + NTPData[5]) + NTPData[6]) + NTPData[7];
                    return 1000 * (((double)temp) / 0x10000);
                }
            }
    
            // Root Dispersion (in milliseconds)
            public double RootDispersion
            {
                get
                {
                    int temp = 0;
                    temp = 256 * (256 * (256 * NTPData[8] + NTPData[9]) + NTPData[10]) + NTPData[11];
                    return 1000 * (((double)temp) / 0x10000);
                }
            }
    
            // Reference Identifier
            public string ReferenceID
            {
                get
                {
                    string val = "";
                    switch (Stratum)
                    {
                        case _Stratum.Unspecified:
                        case _Stratum.PrimaryReference:
                            val += Convert.ToChar(NTPData[offReferenceID + 0]);
                            val += Convert.ToChar(NTPData[offReferenceID + 1]);
                            val += Convert.ToChar(NTPData[offReferenceID + 2]);
                            val += Convert.ToChar(NTPData[offReferenceID + 3]);
                            break;
                        case _Stratum.SecondaryReference:
                            ////     switch(VersionNumber)
                            ////     {
                            ////      case 3: // Version 3, Reference ID is an IPv4 address
                            ////       string Address = NTPData[offReferenceID + 0].ToString() + "." +
                            ////        NTPData[offReferenceID + 1].ToString() + "." +
                            ////        NTPData[offReferenceID + 2].ToString() + "." +
                            ////        NTPData[offReferenceID + 3].ToString();
                            ////       try
                            ////       {
                            ////        IPAddress RefAddr = new IPAddress(Address);
                            ////        IPHostEntry Host = DNS.GetHostByAddr(RefAddr);
                            ////        val = Host.Hostname + " (" + Address + ")";
                            ////       }
                            ////       catch(Exception)
                            ////       {
                            ////        val = "N/A";
                            ////       }
                            ////     
                            ////       break;
                            ////      case 4: // Version 4, Reference ID is the timestamp of last update
                            ////       DateTime time = ComputeDate(GetMilliSeconds(offReferenceID));
                            ////       // Take care of the time zone
                            ////       long offset = TimeZone.CurrentTimeZone.GetUTCOffset(DateTime.Now);
                            ////       TimeSpan offspan = TimeSpan.FromTicks(offset);
                            ////       val = (time + offspan).ToString();
                            ////       break;
                            ////      default:
                            ////       val = "N/A";
                            ////     }
                            break;
                    }
    
                    return val;
                }
            }
    
            // Reference Timestamp
            public DateTime ReferenceTimestamp
            {
                get
                {
                    DateTime time = ComputeDate(GetMilliSeconds(offReferenceTimestamp));
                    // Take care of the time zone
                    long offset = Convert.ToInt64(TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now));
                    TimeSpan offspan = TimeSpan.FromTicks(offset);
                    return time + offspan;
                }
            }
    
            // Originate Timestamp
            public DateTime OriginateTimestamp
            {
                get
                {
                    return ComputeDate(GetMilliSeconds(offOriginateTimestamp));
                }
            }
    
            // Receive Timestamp
            public DateTime ReceiveTimestamp
            {
                get
                {
                    DateTime time = ComputeDate(GetMilliSeconds(offReceiveTimestamp));
                    // Take care of the time zone
                    long offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks;
                    TimeSpan offspan = TimeSpan.FromTicks(offset);
                    return time + offspan;
                }
            }
    
            // Transmit Timestamp
            public DateTime TransmitTimestamp
            {
                get
                {
                    DateTime time = ComputeDate(GetMilliSeconds(offTransmitTimestamp));
                    // Take care of the time zone    
                    long offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks;
                    TimeSpan offspan = TimeSpan.FromTicks(offset);
                    return time + offspan;
                }
                set
                {
                    SetDate(offTransmitTimestamp, value);
                }
            }
    
            // Reception Timestamp
            public DateTime ReceptionTimestamp;
    
            // Round trip delay (in milliseconds)
            public int RoundTripDelay
            {
                get
                {
                    TimeSpan span = (ReceiveTimestamp - OriginateTimestamp) + (ReceptionTimestamp - TransmitTimestamp);
                    return (int)span.TotalMilliseconds;
                }
            }
    
            // Local clock offset (in milliseconds)
            public int LocalClockOffset
            {
                get
                {
                    TimeSpan span = (ReceiveTimestamp - OriginateTimestamp) - (ReceptionTimestamp - TransmitTimestamp);
                    return (int)(span.TotalMilliseconds / 2);
                }
            }
    
            // Compute date, given the number of milliseconds since January 1, 1900
            private DateTime ComputeDate(ulong milliseconds)
            {
                TimeSpan span = TimeSpan.FromMilliseconds((double)milliseconds);
                DateTime time = new DateTime(1900, 1, 1);
                time += span;
                return time;
            }
    
            // Compute the number of milliseconds, given the offset of a 8-byte array
            private ulong GetMilliSeconds(byte offset)
            {
                ulong intpart = 0, fractpart = 0;
    
                for (int i = 0; i <= 3; i++)
                {
                    intpart = 256 * intpart + NTPData[offset + i];
                }
                for (int i = 4; i <= 7; i++)
                {
                    fractpart = 256 * fractpart + NTPData[offset + i];
                }
                ulong milliseconds = intpart * 1000 + (fractpart * 1000) / 0x100000000L;
                return milliseconds;
            }
    
            // Compute the 8-byte array, given the date
            private void SetDate(byte offset, DateTime date)
            {
                ulong intpart = 0, fractpart = 0;
                DateTime StartOfCentury = new DateTime(1900, 1, 1, 0, 0, 0); // January 1, 1900 12:00 AM
    
                ulong milliseconds = (ulong)(date - StartOfCentury).TotalMilliseconds;
                intpart = milliseconds / 1000;
                fractpart = ((milliseconds % 1000) * 0x100000000L) / 1000;
    
                ulong temp = intpart;
                for (int i = 3; i >= 0; i--)
                {
                    NTPData[offset + i] = (byte)(temp % 256);
                    temp = temp / 256;
                }
    
                temp = fractpart;
                for (int i = 7; i >= 4; i--)
                {
                    NTPData[offset + i] = (byte)(temp % 256);
                    temp = temp / 256;
                }
            }
    
            // Initialize the NTPClient data
            private void Initialize()
            {
                // Set version number to 4 and Mode to 3 (client)
                NTPData[0] = 0x1B;
                // Initialize all other fields with 0
                for (int i = 1; i < 48; i++)
                {
                    NTPData[i] = 0;
                }
                // Initialize the transmit timestamp
                TransmitTimestamp = DateTime.Now;
            }
    
            // Connect to the time server
            public void Connect()
            {
                try
                {
                    IPAddress hostadd = IPAddress.Parse(TimeServer);
                    IPEndPoint EPhost = new IPEndPoint(hostadd, Convert.ToInt32(TimePort));
    
                    UdpClient TimeSocket = new UdpClient();
                    TimeSocket.Connect(EPhost);
                    Initialize();
                    TimeSocket.Send(NTPData, NTPData.Length);
                    NTPData = TimeSocket.Receive(ref EPhost);
                    if (!IsResponseValid())
                    {
                        throw new Exception("Invalid response from " + TimeServer);
                    }
                    ReceptionTimestamp = DateTime.Now;
                }
                catch (SocketException e)
                {
                    throw new Exception(e.Message);
                }
            }
    
            // Check if the response from server is valid
            public bool IsResponseValid()
            {
                if (NTPData.Length < NTPDataLength || Mode != _Mode.Server)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
    
            // Converts the object to string
            public override string ToString()
            {
                string str;
    
                str = "Leap Indicator: ";
                switch (LeapIndicator)
                {
                    case _LeapIndicator.NoWarning:
                        str += "No warning";
                        break;
                    case _LeapIndicator.LastMinute61:
                        str += "Last minute has 61 seconds";
                        break;
                    case _LeapIndicator.LastMinute59:
                        str += "Last minute has 59 seconds";
                        break;
                    case _LeapIndicator.Alarm:
                        str += "Alarm Condition (clock not synchronized)";
                        break;
                }
                str += "
    Version number: " + VersionNumber.ToString() + "
    ";
                str += "Mode: ";
                switch (Mode)
                {
                    case _Mode.Unknown:
                        str += "Unknown";
                        break;
                    case _Mode.SymmetricActive:
                        str += "Symmetric Active";
                        break;
                    case _Mode.SymmetricPassive:
                        str += "Symmetric Pasive";
                        break;
                    case _Mode.Client:
                        str += "Client";
                        break;
                    case _Mode.Server:
                        str += "Server";
                        break;
                    case _Mode.Broadcast:
                        str += "Broadcast";
                        break;
                }
                str += "
    Stratum: ";
                switch (Stratum)
                {
                    case _Stratum.Unspecified:
                    case _Stratum.Reserved:
                        str += "Unspecified";
                        break;
                    case _Stratum.PrimaryReference:
                        str += "Primary Reference";
                        break;
                    case _Stratum.SecondaryReference:
                        str += "Secondary Reference";
                        break;
                }
                str += "
    Local time: " + TransmitTimestamp.ToString();
                str += "
    Precision: " + Precision.ToString() + " ms";
                str += "
    Poll Interval: " + PollInterval.ToString() + " s";
                str += "
    Reference ID: " + ReferenceID.ToString();
                str += "
    Root Dispersion: " + RootDispersion.ToString() + " ms";
                str += "
    Round Trip Delay: " + RoundTripDelay.ToString() + " ms";
                str += "
    Local Clock Offset: " + LocalClockOffset.ToString() + " ms";
                str += "
    ";
    
                return str;
            }
    
            // The URL of the time server we're connecting to
            private string TimeServer;
            private string TimePort;
    
            public SNTPTimeClient(string host, string port)
            {
                TimeServer = host;
                TimePort = port;
            }
        }
    }
    
    调用:
                SNTPTime.SNTPTimeClient client = new SNTPTime.SNTPTimeClient("210.72.145.44", "123");
                client.Connect();
                string strTest = client.ToString();
     
    View Code

    获取当前系统时间

    --DateTime 数字型
    System.DateTime currentTime=new System.DateTime();
    取当前年月日时分秒 currentTime=System.DateTime.Now;
    取当前年 int 年=currentTime.Year;
    取当前月 int 月=currentTime.Month;
    取当前日 int 日=currentTime.Day;
    取当前时 int 时=currentTime.Hour;
    取当前分 int 分=currentTime.Minute;
    取当前秒 int 秒=currentTime.Second;
    取当前毫秒 int 毫秒=currentTime.Millisecond; (变量可用中文)
    取中文日期显示——年月日时分 string strY=currentTime.ToString("f"); //不显示秒
    取中文日期显示_年月 string strYM=currentTime.ToString("y");
    取中文日期显示_月日 string strMD=currentTime.ToString("m");
    取当前年月日,格式为:2003-9-23 string strYMD=currentTime.ToString("d");
    取当前时分,格式为:14:24 string strT=currentTime.ToString("t");
    DateTime.Now.ToString();//获取当前系统时间 完整的日期和时间
    DateTime.Now.ToLongDateString();//只显示日期 xxxx年xx月xx日 ,一个是长日期
    DateTime.Now.ToShortDateString();//只显示日期 xxxx-xx-xx 一个是短日期
    //今天 DateTime.Now.Date.ToShortDateString();
    //昨天 的 DateTime.Now.AddDays(-1).ToShortDateString();
    //明天 的 DateTime.Now.AddDays(1).ToShortDateString();

    //本周(注意这里的每一周是从周日始至周六止)
    DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString();
    DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString();
    //上周,上周就是本周再减去7天
    DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString();
    DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString();
    //下周 本周再加上7天
    DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString();
    DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString();
    //本月 本月的第一天是1号,最后一天就是下个月一号再减一天。
    DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1"; //第一天
    DateTime.Parse(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1").AddMonths(1).AddDays(-1).ToShortDateString();//最后一天
    另一种方法:
    DateTime now = DateTime.Now;
    DateTime d1 = new DateTime(now.Year, now.Month, 1); //本月第一天
    DateTime d2 = d1.AddMonths(1).AddDays(-1); //本月最后一天
    PS:
    DateTime.Now.DayOfWeek.ToString();//英文星期显示,Wednesday
    (int)DateTime.Now.DayOfWeek 数字,若是周三,结果对应为3
    DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("zh-cn")); //中文星期显示
    DateTime.Now.ToString("dddd");//中文星期显示
    DateTime.Now.ToString("dddd,MMMM,dd ,yyyy", new System.Globalization.DateTimeFormatInfo());//显示日期格式Friday,July, 01,2009
    DateTime.Now.ToString("dddd,dd MMMM,yyyy") //输出 星期三,30 一月,2008
    出处:http://msdn.microsoft.com/zh-cn/vstudio/bb762911(VS.95).aspx,如何:从特定日期中提取星期几
    datetime类型在tostring()format的格式设置
    参数format格式详细用法
     格式字符 关联属性/说明
     d ShortDatePattern
     D LongDatePattern
     f 完整日期和时间(长日期和短时间)
     F FullDateTimePattern(长日期和长时间)
     g 常规(短日期和短时间)
     G 常规(短日期和长时间)
     m、M MonthDayPattern
     r、R RFC1123Pattern
     s 使用当地时间的 SortableDateTimePattern(基于 ISO 8601)
     t ShortTimePattern
     T LongTimePattern
     u UniversalSortableDateTimePattern 用于显示通用时间的格式
     U 使用通用时间的完整日期和时间(长日期和长时间)
     y、Y YearMonthPattern
    下表列出了可被合并以构造自定义模式的模式。这些模式是区分大小写的
    d 月中的某一天。一位数的日期没有前导零。
     dd 月中的某一天。一位数的日期有一个前导零。
     ddd 周中某天的缩写名称,在 AbbreviatedDayNames 中定义。
     dddd 周中某天的完整名称,在 DayNames 中定义。
     M 月份数字。一位数的月份没有前导零。
     MM 月份数字。一位数的月份有一个前导零。
     MMM 月份的缩写名称,在 AbbreviatedMonthNames 中定义。
     MMMM 月份的完整名称,在 MonthNames 中定义。
     y 不包含纪元的年份。如果不包含纪元的年份小于 10,则显示不具有前导零的年份。
     yy 不包含纪元的年份。如果不包含纪元的年份小于 10,则显示具有前导零的年份。
     yyyy 包括纪元的四位数的年份。
     gg 时期或纪元。如果要设置格式的日期不具有关联的时期或纪元字符串,则忽略该模式。
    h 12 小时制的小时。一位数的小时数没有前导零。
     hh 12 小时制的小时。一位数的小时数有前导零。
     H 24 小时制的小时。一位数的小时数没有前导零。
     HH 24 小时制的小时。一位数的小时数有前导零。

    获取北京时间多种方法

          #region 获取网络时间
              /// <summary>
            /// 获取中国国家授时中心网络服务器时间发布的当前时间
             /// </summary>
            /// <returns></returns>
            public static DateTime GetChineseDateTime()
            {
                DateTime res = DateTime.MinValue;
                try
                {
                    string url = "http://www.time.ac.cn/stime.asp";
                    HttpHelper helper = new HttpHelper();
                    helper.Encoding = Encoding.Default;
                    string html = helper.GetHtml(url);
                    string patDt = @"d{4}年d{1,2}月d{1,2}日";
                    string patHr = @"hrss+=s+d{1,2}";
                    string patMn = @"mins+=s+d{1,2}";
                    string patSc = @"secs+=s+d{1,2}";
                    Regex regDt = new Regex(patDt);
                    Regex regHr = new Regex(patHr);
                    Regex regMn = new Regex(patMn);
                    Regex regSc = new Regex(patSc);
    
                    res = DateTime.Parse(regDt.Match(html).Value);
                    int hr = GetInt(regHr.Match(html).Value, false);
                    int mn = GetInt(regMn.Match(html).Value, false);
                    int sc = GetInt(regSc.Match(html).Value, false);
                    res = res.AddHours(hr).AddMinutes(mn).AddSeconds(sc);
                }
                catch { }
                return res;
            }
    
            /// <summary>
            /// 从指定的字符串中获取整数
            /// </summary>
            /// <param name="origin">原始的字符串</param>
            /// <param name="fullMatch">是否完全匹配,若为false,则返回字符串中的第一个整数数字</param>
            /// <returns>整数数字</returns>
            private static int GetInt(string origin, bool fullMatch)
            {
                if (string.IsNullOrEmpty(origin))
                {
                    return 0;
                }
                origin = origin.Trim();
                if (!fullMatch)
                {
                    string pat = @"-?d+";
                    Regex reg = new Regex(pat);
                    origin = reg.Match(origin.Trim()).Value;
                }
                int res = 0;
                int.TryParse(origin, out res);
                return res;
            }
            #endregion
    
    
           /// <summary>
            /// 获取标准北京时间1
            /// </summary>
            /// <returns></returns>
            public static DateTime GetStandardTime()
            {
                //<?xml version="1.0" encoding="GB2312" ?>
                //- <ntsc>
                //- <time>
                // <year>2011</year>
                // <month>7</month>
                // <day>10</day>
                // <Weekday />
                // <hour>19</hour>
                // <minite>45</minite>
                // <second>37</second>
                // <Millisecond />
                // </time>
                //  </ntsc>
               DateTime dt;
                WebRequest wrt = null;
                WebResponse wrp = null;
                try
                {
                    wrt = WebRequest.Create("http://www.time.ac.cn/timeflash.asp?user=flash");
                    wrt.Credentials = CredentialCache.DefaultCredentials;
    
                    wrp = wrt.GetResponse();
                    StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.UTF8);
                    string html = sr.ReadToEnd();
    
                    sr.Close();
                    wrp.Close();
    
                    int yearIndex = html.IndexOf("<year>") + 6;
                    int monthIndex = html.IndexOf("<month>") + 7;
                    int dayIndex = html.IndexOf("<day>") + 5;
                    int hourIndex = html.IndexOf("<hour>") + 6;
                    int miniteIndex = html.IndexOf("<minite>") + 8;
                    int secondIndex = html.IndexOf("<second>") + 8;
    
                    string year = html.Substring(yearIndex, html.IndexOf("</year>") - yearIndex);
                    string month = html.Substring(monthIndex, html.IndexOf("</month>") - monthIndex); ;
                    string day = html.Substring(dayIndex, html.IndexOf("</day>") - dayIndex);
                    string hour = html.Substring(hourIndex, html.IndexOf("</hour>") - hourIndex);
                    string minite = html.Substring(miniteIndex, html.IndexOf("</minite>") - miniteIndex);
                    string second = html.Substring(secondIndex, html.IndexOf("</second>") - secondIndex);
                    dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
                }
                catch (WebException)
                {
                    return DateTime.Parse("2011-1-1");
                }
                catch (Exception)
                {
                    return DateTime.Parse("2011-1-1");
                }
                finally
                {
                    if (wrp != null)
                        wrp.Close();
                    if (wrt != null)
                        wrt.Abort();
                }
                return dt;
            }
    
            /// <summary>
            /// 获取标准北京时间2
            /// </summary>
            /// <returns></returns>
            public static DateTime GetBeijingTime()
            {
                //t0 = new Date().getTime();
                //nyear = 2011;
                //nmonth = 7;
                //nday = 5;
                //nwday = 2;
                //nhrs = 17;
                //nmin = 12;
                //nsec = 12;
               DateTime dt;
                WebRequest wrt = null;
                WebResponse wrp = null;
                try
                {
                    wrt = WebRequest.Create("http://www.beijing-time.org/time.asp");
                    wrp = wrt.GetResponse();
    
                    string html = string.Empty;
                    using (Stream stream = wrp.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                        {
                            html = sr.ReadToEnd();
                        }
                    }
    
                    string[] tempArray = html.Split(';');
                    for (int i = 0; i < tempArray.Length; i++)
                    {
                        tempArray[i] = tempArray[i].Replace("
    ", "");
                    }
    
                    string year = tempArray[1].Substring(tempArray[1].IndexOf("nyear=") + 6);
                    string month = tempArray[2].Substring(tempArray[2].IndexOf("nmonth=") + 7);
                    string day = tempArray[3].Substring(tempArray[3].IndexOf("nday=") + 5);
                    string hour = tempArray[5].Substring(tempArray[5].IndexOf("nhrs=") + 5);
                    string minite = tempArray[6].Substring(tempArray[6].IndexOf("nmin=") + 5);
                    string second = tempArray[7].Substring(tempArray[7].IndexOf("nsec=") + 5);
                    dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
                }
                catch (WebException)
                {
                    return DateTime.Parse("2011-1-1");
                }
                catch (Exception)
                {
                    return DateTime.Parse("2011-1-1");
                }
                finally
                {
                    if (wrp != null)
                        wrp.Close();
                    if (wrt != null)
                        wrt.Abort();
                }
                return dt;
            }
    
    
           /// <summary>
            /// 获取标准北京时间
             /// </summary>
            /// <returns></returns>
            public static DateTime DataStandardTime()
            {
                DateTime dt;
    
                //返回国际标准时间
                //只使用的时间服务器的IP地址,未使用域名
                try
                {
                    string[,] 时间服务器 = new string[14, 2];
                    int[] 搜索顺序 = new int[] { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 };
                    时间服务器[0, 0] = "time-a.nist.gov";
                    时间服务器[0, 1] = "129.6.15.28";
                    时间服务器[1, 0] = "time-b.nist.gov";
                    时间服务器[1, 1] = "129.6.15.29";
                    时间服务器[2, 0] = "time-a.timefreq.bldrdoc.gov";
                    时间服务器[2, 1] = "132.163.4.101";
                    时间服务器[3, 0] = "time-b.timefreq.bldrdoc.gov";
                    时间服务器[3, 1] = "132.163.4.102";
                    时间服务器[4, 0] = "time-c.timefreq.bldrdoc.gov";
                    时间服务器[4, 1] = "132.163.4.103";
                    时间服务器[5, 0] = "utcnist.colorado.edu";
                    时间服务器[5, 1] = "128.138.140.44";
                    时间服务器[6, 0] = "time.nist.gov";
                    时间服务器[6, 1] = "192.43.244.18";
                    时间服务器[7, 0] = "time-nw.nist.gov";
                    时间服务器[7, 1] = "131.107.1.10";
                    时间服务器[8, 0] = "nist1.symmetricom.com";
                    时间服务器[8, 1] = "69.25.96.13";
                    时间服务器[9, 0] = "nist1-dc.glassey.com";
                    时间服务器[9, 1] = "216.200.93.8";
                    时间服务器[10, 0] = "nist1-ny.glassey.com";
                    时间服务器[10, 1] = "208.184.49.9";
                    时间服务器[11, 0] = "nist1-sj.glassey.com";
                    时间服务器[11, 1] = "207.126.98.204";
                    时间服务器[12, 0] = "nist1.aol-ca.truetime.com";
                    时间服务器[12, 1] = "207.200.81.113";
                    时间服务器[13, 0] = "nist1.aol-va.truetime.com";
                    时间服务器[13, 1] = "64.236.96.53";
                    int portNum = 13;
                    string hostName;
                    byte[] bytes = new byte[1024];
                    int bytesRead = 0;
                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                    for (int i = 0; i < 13; i++)
                    {
                        hostName = 时间服务器[搜索顺序[i], 1];
                        try
                        {
                            client.Connect(hostName, portNum);
                            System.Net.Sockets.NetworkStream ns = client.GetStream();
                            bytesRead = ns.Read(bytes, 0, bytes.Length);
                            client.Close();
                            break;
                        }
                        catch (System.Exception)
                        {
                        }
                    }
                    char[] sp = new char[1];
                    sp[0] = ' ';
                    dt = new DateTime();
                    string str1;
                    str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead);
    
                    string[] s;
                    s = str1.Split(sp);
                    if (s.Length >= 2)
                    {
                        dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间
                        dt = dt.AddHours(8);//得到北京时间*/
                   }
                    else
                    {
                        dt = DateTime.Parse("2011-1-1");
                    }
                }
                catch (Exception)
                {
                    dt = DateTime.Parse("2011-1-1");
                }
                return dt;
            }
    
    
    调用示例:
    
     DateTime dt = Common.GetBeijingTime();// Common.GetStandardTime();
     if (dt.ToString() == "2011-1-1 0:00:00")
      {
           MessageBox.Show("网络异常,不能启动本程序!");
           Application.Exit();
           return;
      }

    时间比较

    use "DateTime.Compare" static method
    DateTime.Compare( dt1, dt2 ) > 0 : dt1 > dt2
    DateTime.Compare( dt1, dt2 ) == 0 : dt1 == dt2
    DateTime.Compare( dt1, dt2 ) < 0 : dt1 < dt2
    /// <summary>
    /// 计算两个日期的时间间隔
    /// </summary>
    /// <param name="DateTime1">第一个日期和时间</param>
    /// <param name="DateTime2">第二个日期和时间</param>
    /// <returns></returns>
    private string DateDiff(DateTime DateTime1, DateTime DateTime2)
    {
    string dateDiff = null;
    
    TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
    TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
    TimeSpan ts = ts1.Subtract(ts2).Duration();
    dateDiff = ts.Days.ToString()+""
    + ts.Hours.ToString()+"小时"
    + ts.Minutes.ToString()+"分钟"
    + ts.Seconds.ToString()+"";
    
    return dateDiff;
    } 

    说明:
    1.DateTime值类型代表了一个从公元0001年1月1日0点0分0秒到公元9999年12月31日23点59分59秒之间的具体日期时刻。因此,你可以用DateTime值类型来描述任何在想象范围之内的时间。一个DateTime值代表了一个具体的时刻
    2.TimeSpan值包含了许多属性与方法,用于访问或处理一个TimeSpan值
    下面的列表涵盖了其中的一部分:
    Add:与另一个TimeSpan值相加。
    Days:返回用天数计算的TimeSpan值。
    Duration:获取TimeSpan的绝对值。
    Hours:返回用小时计算的TimeSpan值
    Milliseconds:返回用毫秒计算的TimeSpan值。
    Minutes:返回用分钟计算的TimeSpan值。
    Negate:返回当前实例的相反数。
    Seconds:返回用秒计算的TimeSpan值。
    Subtract:从中减去另一个TimeSpan值。
    Ticks:返回TimeSpan值的tick数。
    TotalDays:返回TimeSpan值表示的天数。
    TotalHours:返回TimeSpan值表示的小时数。
    TotalMilliseconds:返回TimeSpan值表示的毫秒数。
    TotalMinutes:返回TimeSpan值表示的分钟数。
    TotalSeconds:返回TimeSpan值表示的秒数。

    时间差的操作

    c#计算时间差重点:

    c#计算时间差函数TimeSpan的应用

    TimeSpan值包含了许多属性与方法,用于访问或处理一个TimeSpan值

    下面的列表涵盖了其中的一部分:

    Add:与另一个TimeSpan值相加。

    Days:返回用天数计算的TimeSpan值。

    Duration:获取TimeSpan的绝对值。

    Hours:返回用小时计算的TimeSpan值

    Milliseconds:返回用毫秒计算的TimeSpan值。

    Minutes:返回用分钟计算的TimeSpan值。

    Negate:返回当前实例的相反数。

    Seconds:返回用秒计算的TimeSpan值。

    Subtract:从中减去另一个TimeSpan值。

    Ticks:返回TimeSpan值的tick数。

    TotalDays:返回TimeSpan值表示的天数。

    TotalHours:返回TimeSpan值表示的小时数。

    TotalMilliseconds:返回TimeSpan值表示的毫秒数。

    TotalMinutes:返回TimeSpan值表示的分钟数。

    TotalSeconds:返回TimeSpan值表示的秒数。

    c#计算时间差实现方法:

    DateTime DateTime1, DateTime2 = DateTime.Now ;//现在时间 DateTime1 =Convert.ToDateTime("2009-04-24 20:00:00"); //设置要求的减的时间 string dateDiff = null; TimeSpan ts1 = new TimeSpan(DateTime1.Ticks); TimeSpan ts2 = new TimeSpan(DateTime2.Ticks); TimeSpan ts = ts1.Subtract(ts2).Duration(); //显示时间 dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒";

    获取网络时间

    using System;
    using System.Data;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Net;
    using System.Net.Sockets;
     
    namespace getInterTime
    {
        struct SystemTime
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
     
            /// <summary>   
            /// 从System.DateTime转换。   
         /// </summary>   
            /// <param name="time">System.DateTime类型的时间。</param>   
            public void FromDateTime(DateTime time)
            {
                wYear = (ushort)time.Year;
                wMonth = (ushort)time.Month;
                wDayOfWeek = (ushort)time.DayOfWeek;
                wDay = (ushort)time.Day;
                wHour = (ushort)time.Hour;
                wMinute = (ushort)time.Minute;
                wSecond = (ushort)time.Second;
                wMilliseconds = (ushort)time.Millisecond;
            }
            /// <summary>   
            /// 转换为System.DateTime类型。   
          /// </summary>   
            /// <returns></returns>   
            public DateTime ToDateTime()
            {
                return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
            }
            /// <summary>   
            /// 静态方法。转换为System.DateTime类型。   
            /// </summary>   
            /// <param name="time">SYSTEMTIME类型的时间。</param>   
            /// <returns></returns>   
            public static DateTime ToDateTime(SystemTime time)
            {
                return time.ToDateTime();
            }
        }
        class Win32API
        {
            [DllImport("Kernel32.dll")]
            public static extern bool SetLocalTime(ref SystemTime Time);
            [DllImport("Kernel32.dll")]
            public static extern void GetLocalTime(ref SystemTime Time);
        }  
        class Program
        {
            static void Main(string[] args)
            {
                getInternetTime();
                Console.ReadLine();
            }
     
            public static void getInternetTime()
            {
                // 记录开始的时间   
                DateTime startDT = DateTime.Now;
     
                //建立IPAddress对象与端口,创建IPEndPoint节点:   
                int port = 13;
                string[] whost = { "time-nw.nist.gov", "5time.nist.gov", "time-a.nist.gov", "time-b.nist.gov", "tick.mit.edu", "time.windows.com", "clock.sgi.com" };
     
                IPHostEntry iphostinfo;
                IPAddress ip;
                IPEndPoint ipe;
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
                c.ReceiveTimeout = 10 * 1000;//设置超时时间   
                string sEX = "";// 接受错误信息   
                // 遍历时间服务器列表   
                foreach (string strHost in whost)
                {
                    try
                    {
                        iphostinfo = Dns.GetHostEntry(strHost);
                        ip = iphostinfo.AddressList[0];
                        ipe = new IPEndPoint(ip, port);
                        c.Connect(ipe);//连接到服务器   
                        if (c.Connected) break;// 如果连接到服务器就跳出   
                    }
                    catch (Exception ex)
                    {
                       
                    }
                }
                //SOCKET同步接受数据   
                byte[] RecvBuffer = new byte[1024];
                int nBytes, nTotalBytes = 0;
                StringBuilder sb = new StringBuilder();
                System.Text.Encoding myE = Encoding.UTF8;
                try
                {
                    while ((nBytes = c.Receive(RecvBuffer, 0, 1024, SocketFlags.None)) > 0)
                    {
                        nTotalBytes += nBytes;
                        sb.Append(myE.GetString(RecvBuffer, 0, nBytes));
                    }
                }
                catch (System.Exception ex)
                {
                
                }
               
                //关闭连接   
                c.Close();
                string[] o = sb.ToString().Split(' '); // 打断字符串   
                TimeSpan k = new TimeSpan();
                k = (TimeSpan)(DateTime.Now - startDT);// 得到开始到现在所消耗的时间   
                DateTime SetDT = Convert.ToDateTime(o[1] + " " + o[2]).Subtract(-k);// 减去中途消耗的时间   
     
                //处置北京时间 +8时   
                SetDT = SetDT.AddHours(8);
     
                //转换System.DateTime到SystemTime   
                SystemTime st = new SystemTime();
                st.FromDateTime(SetDT);
                Console.WriteLine(st.ToDateTime().ToString()); //这里可以输出获得的互联网时间
                //Win32API.SetLocalTime(ref st);//如果选择不输出,也可以使用API设置为系统的时间,API函数申明见上面的Win32API类   
            }
        }
    }
     
     
    View Code
  • 相关阅读:
    块级元素和内联元素
    cookie和session 区别
    hihernate一对多关联映射
    --查询50到80行数据
    单表查询
    表空间 用户
    进程遍历模块遍历
    字符转换函数
    控件综合2
    清理文件2
  • 原文地址:https://www.cnblogs.com/blogpro/p/11340708.html
Copyright © 2020-2023  润新知