来自:http://my.csdn.net/jocce_11/code/detail/35369
主要是抓取:http://www.beijing-time.org/time.asp 的时间
01.
using
System;
02.
using
System.Collections.Generic;
03.
using
System.Linq;
04.
using
System.Text;
05.
using
System.IO;
06.
using
System.Net;
07.
using
System.Net.Sockets;
08.
using
System.Text.RegularExpressions;
09.
using
System.Runtime.InteropServices;
10.
using
System.Runtime;
11.
12.
13.
14.
/// <summary>
15.
/// 网络时间
16.
/// </summary>
17.
public
class
NetTime
18. {
19.
20.
/// <summary>
21.
/// 获取标准北京时间,读取http://www.beijing-time.org/time.asp
22.
/// </summary>
23.
/// <returns>返回网络时间</returns>
24.
public
DateTime GetBeijingTime()
25. {
26.
27. DateTime dt;
28. WebRequest wrt =
null
;
29. WebResponse wrp =
null
;
30.
try
31. {
33. wrp = wrt.GetResponse();
34.
35.
string
html =
string
.Empty;
36.
using
(Stream stream = wrp.GetResponseStream())
37. {
38.
using
(StreamReader sr =
new
StreamReader(stream, Encoding.UTF8))
39. {
40. html = sr.ReadToEnd();
41. }
42. }
43.
44.
string
[] tempArray = html.Split(
';'
);
45.
for
(
int
i = 0; i < tempArray.Length; i++)
46. {
47. tempArray[i] = tempArray[i].Replace(
"rn"
,
""
);
48. }
49.
50.
string
year = tempArray[1].Split(
'='
)[1];
51.
string
month = tempArray[2].Split(
'='
)[1];
52.
string
day = tempArray[3].Split(
'='
)[1];
53.
string
hour = tempArray[5].Split(
'='
)[1];
54.
string
minite = tempArray[6].Split(
'='
)[1];
55.
string
second = tempArray[7].Split(
'='
)[1];
56.
57. dt = DateTime.Parse(year +
"-"
+ month +
"-"
+ day +
" "
+ hour +
":"
+ minite +
":"
+ second);
58. }
59.
catch
(WebException)
60. {
61.
return
DateTime.Parse(
"2011-1-1"
);
62. }
63.
catch
(Exception)
64. {
65.
return
DateTime.Parse(
"2011-1-1"
);
66. }
67.
finally
68. {
69.
if
(wrp !=
null
)
70. wrp.Close();
71.
if
(wrt !=
null
)
72. wrt.Abort();
73. }
74.
return
dt;
75.
76. }
77. }
描述:客户的机器的系统时间经常出错,导致给他们做的软件无法正常使用,所以后来就加了一个同步网络时间的小功能。实现起来很简单,但是却很使用。 这个小功能就是先获取网络时间,然后将系统的时间修改成从网络获得的时间。下面是具体的实现: 获取网络时间: