C#获取时间的操作
序
写代码需要用到超时退出,但是全部写定时器的话就会比较麻烦,
所以想到获取系统时间,通过判断是否超过系统时间,超过系统时间的话就退出。
获得系统时间的代码如下
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; (变量可用中文)
获取完还没有结束,在实际的定时函数中,所需要使用的一般是秒或者毫秒的判断,所以还需要将得到的数据转换成一个固定的数字来判断。
参考代码如下
代码中的“time” 就是现在的时间显示格式如下:2022.1.18.9.46.15.113
本代码的特色是将中文变量添加到了代码中间,可以实现中文编程。奥利给。。。ヾ(◍°∇°◍)ノ゙
(❀ฺ´∀`❀ฺ)ノ✧*。٩(ˊᗜˋ*)و✧*。✧⁺⸜(●˙▾˙●)⸝⁺✧✺◟(∗❛ัᴗ❛ั∗)◞✺
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 time = 年.ToString() + "." + 月.ToString() + "." + 日.ToString() + "." + 时.ToString() + "." + 分.ToString() + "." + 秒.ToString() + "." + 毫秒.ToString();
再增加一个保存文件,且将时间保存到文件中去
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 time = 年.ToString() + "." + 月.ToString() + "." + 日.ToString() + "." + 时.ToString() + "." + 分.ToString() + "." + 秒.ToString() + "." + 毫秒.ToString();
string path = "Write Clk Trim.txt";
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(time);
sw.WriteLine(SaveData);
}
计算程序运行的时间
//声明变量
System.DateTime currentTime = new System.DateTime();
System.DateTime currentTime1 = new System.DateTime();
currentTime = System.DateTime.Now;
//
//代码运行部分
//
//
//在两个时间中,加入代码运行的部分,
//相减,可以得到代码运行的时间
currentTime1 = System.DateTime.Now;
//输出时间
Debug.WriteLine(currentTime1-currentTime);