对于B/S程序,系统种用到的时间一般都是服务器时间,我们的取法经常就是 DateTime.Now;然而,在某些特殊的项目中,可能需要让客户自己更改系统时间,比如在用户需要补录一张前几天的单据,这时,考虑到还有其它用户也在同时使用系统,改服务器时间是不可能的,为此,我们可以设置一中有别于服务器系统时间的用户时间。可以让用户在登录讲时间保存到Session中,然后在需要用的时候从Session中把时间取出来,这样,让每个客户都有了自己的时间系统。代码如下:
先设计一个时间类:
用户登录的代码就很简单了:
private void Button1_Click(object sender, System.EventArgs e)
{
CurrentTime.UserTime = DateTime.Parse(TextBox1.Text);
}
![]()
private void Button2_Click(object sender, System.EventArgs e)
{
Label1.Text = CurrentTime.UserTime.ToString();
}
先设计一个时间类:
1
public class CurrentTime
2
{
3
private CurrentTime()
4
{
5
}
6![]()
7
/// <summary>
8
/// 用户时间
9
/// </summary>
10
public static DateTime UserTime
11
{
12
set
13
{
14
// 仅保存日期,时间获取当前系统时间
15
DateTime t = (DateTime)value;
16
HttpContext.Current.Session["USER_TIME"] = t.ToString("yyyy-MM-dd");
17
}
18
get
19
{
20
// 获取时间,返回保存的日期和当前的时间
21
if (HttpContext.Current.Session["USER_TIME"] != null)
22
{
23
string strDateTime = HttpContext.Current.Session["USER_TIME"].ToString();
24
DateTime d = DateTime.Parse(strDateTime + DateTime.Now.ToString(" HH:mm:ss"));
25
return d;
26
}
27
else
28
{
29
// 如果没有保存,则返回当前时间
30
return DateTime.Now;
31
}
32
}
33
}
34![]()
35
/// <summary>
36
/// 系统时间
37
/// </summary>
38
public static DateTime SystemTime
39
{
40
get
41
{
42
return DateTime.Now;
43
}
44
}
45
}
当需要取用户时间就是 CurrentTime.UserTime,取系统时间就是CurrentUser.SystemTime,之所以讲系统时间也提供出来,两个原因,1,将时间相关的方法和属性封装到一个类中,达到封装的目的。2,为以后系统扩充留下空隙,某一天用户提出个系统时间要作一些改变,就能轻易实现了
public class CurrentTime2
{3
private CurrentTime()4
{5
}6

7
/// <summary>8
/// 用户时间9
/// </summary>10
public static DateTime UserTime11
{12
set13
{14
// 仅保存日期,时间获取当前系统时间15
DateTime t = (DateTime)value;16
HttpContext.Current.Session["USER_TIME"] = t.ToString("yyyy-MM-dd");17
}18
get19
{20
// 获取时间,返回保存的日期和当前的时间21
if (HttpContext.Current.Session["USER_TIME"] != null)22
{23
string strDateTime = HttpContext.Current.Session["USER_TIME"].ToString();24
DateTime d = DateTime.Parse(strDateTime + DateTime.Now.ToString(" HH:mm:ss"));25
return d;26
}27
else28
{29
// 如果没有保存,则返回当前时间30
return DateTime.Now;31
} 32
}33
}34

35
/// <summary>36
/// 系统时间37
/// </summary>38
public static DateTime SystemTime39
{40
get41
{42
return DateTime.Now;43
}44
}45
}用户登录的代码就很简单了:
private void Button1_Click(object sender, System.EventArgs e)
{
CurrentTime.UserTime = DateTime.Parse(TextBox1.Text);
}
private void Button2_Click(object sender, System.EventArgs e)
{
Label1.Text = CurrentTime.UserTime.ToString();
}

浙公网安备 33010602011771号