初始化 DateTime now = DateTime.Now;
获取时间
/获取日期+时间 DateTime.Now.ToString(); // 2008-9-4 20:02:10 DateTime.Now.ToLocalTime().ToString(); // 2008-9-4 20:12:12 //获取日期 DateTime.Now.ToLongDateString().ToString(); // 2008年9月4日 DateTime.Now.ToShortDateString().ToString(); // 2008/9/4 DateTime.Now.ToString("yyyy-MM-dd"); // 2008-09-04 DateTime.Now.Date.ToString(); // 2008-9-4 0:00:00 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //获取时间 DateTime.Now.ToLongTimeString().ToString(); // 20:16:16 DateTime.Now.ToShortTimeString().ToString(); // 20:16 DateTime.Now.TimeOfDay.ToString(); // 20:33:50.7187500 // 24小时制 DateTime.Now.ToString("HH:mm:ss"); // 20:22:33 24小时制 // 毫秒 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") // 单独获取日期、时间 .net 6 DateOnly dateOnly = new(2021, 9, 25); Console.WriteLine(dateOnly); TimeOnly timeOnly = new(19, 0, 0); Console.WriteLine(timeOnly); DateOnly dateOnlyFromDate = DateOnly.FromDateTime(DateTime.Now); Console.WriteLine(dateOnlyFromDate); TimeOnly timeOnlyFromDate = TimeOnly.FromDateTime(DateTime.Now); Console.WriteLine(timeOnlyFromDate); //其他 DateTime.ToFileTime().ToString(); // 128650040212500000 DateTime.Now.ToFileTimeUtc().ToString(); // 128650040772968750 DateTime.Now.ToOADate().ToString(); // 39695.8461709606 DateTime.Now.ToUniversalTime().ToString(); // 2008-9-4 12:19:14 DateTime.Now.Year.ToString(); 获取年份 // 2008 DateTime.Now.Month.ToString(); 获取月份 // 9 DateTime.Now.DayOfWeek.ToString(); 获取星期 // Thursday DateTime.Now.DayOfYear.ToString(); 获取第几天 // 248 DateTime.Now.Hour.ToString(); 获取小时 // 20 DateTime.Now.Minute.ToString(); 获取分钟 // 31 DateTime.Now.Second.ToString(); 获取秒数 // 45 //n为一个数,可以数整数,也可以事小数 dt.AddYears(n).ToString(); //时间加n年 dt.AddDays(n).ToString(); //加n天 dt.AddHours(n).ToString(); //加n小时 dt.AddMonths(n).ToString(); //加n个月 dt.AddSeconds(n).ToString(); //加n秒 dt.AddMinutes(n).ToString(); //加n分
字符串转时间 var dateTime = DateTime.ParseExact("2020-01-04 16:54", "yyyy-MM-dd HH:mm", null); var strDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); string strFormat = "yyyy-MM-dd HH:mm:ss"; skip_retryFormat: string strDate = ""; try { var dateTime = DateTime.ParseExact(colsStr[0], strFormat, null); strDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); } catch(System.FormatException ex) { if (strFormat != "yyyy/M/d HH:mm:ss") { strFormat = "yyyy/M/d HH:mm:ss"; goto skip_retryFormat; }else { MessageBox.Show("数据日期格式不支持,请联系技术支持"); } }
加减 //昨天,就是今天的日期减一 DateTime.Now.AddDays(-1).ToShortDateString(); //明天,同理,加一 DateTime.Now.AddDays(1).ToShortDateString();
函数执行时间 static void SubTest() { DateTime beforDT = System.DateTime.Now; //耗时的代码 DateTime afterDT = System.DateTime.Now; TimeSpan ts = afterDT.Subtract(beforDT); Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds); // {ts.Minutes}分{ts.Seconds}秒 } static void SubTest() { Stopwatch sw = new Stopwatch(); sw.Start(); //耗时巨大的代码 sw.Stop(); TimeSpan ts2 = sw.Elapsed; Console.WriteLine("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds); } [System.Runtime.InteropServices.DllImport("Kernel32.dll")] static extern bool QueryPerformanceCounter(ref long count); [System.Runtime.InteropServices.DllImport("Kernel32.dll")] static extern bool QueryPerformanceFrequency(ref long count); static void SubTest() { long count = 0; long count1 = 0; long freq = 0; double result = 0; QueryPerformanceFrequency(ref freq); QueryPerformanceCounter(ref count); //耗时巨大的代码 QueryPerformanceCounter(ref count1); count = count1 - count; result = (double)(count) / (double)freq; Console.WriteLine("QueryPerformanceCounter耗时: {0} 秒", result); }
timer System.Timers.Timer 不会抛异常 精度大约在10ms~20ms之间
//实例化Timer类,设置间隔时间为10000毫秒; System.Timers.Timer t = new System.Timers.Timer(10000); //到达时间的时候执行事件; t.Elapsed += new System.Timers.ElapsedEventHandler(theout); //设置是执行一次(false)还是一直执行(true); t.AutoReset = true; //需要调用 timer.Start()或者timer.Enabled = true来启动它, timer.Start()的内部原理还是设置timer.Enabled = true; t.Enabled = true; public void theout(object source, System.Timers.ElapsedEventArgs e) { }
Threading.Timer 会抛异常 精度也只能达到20ms
private System.Threading.Timer timerClose; timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 5000, 0); private void timerCall(object obj) { timerClose.Dispose(); this.Close(); }
DispatcherTimer(WPF timer) 需要注意的是在wpf中涉及到界面操作的话,一定要使用 DispatcherTime, DispatcherTimer 是为wpf专门设计的,不然的话会提示界面资源被其他线程所拥有而无法更新界面。
public DispatcherTimerSample() { InitializeComponent(); DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += timer_Tick; timer.Start(); } void timer_Tick(object sender, EventArgs e) { lblTime.Content = DateTime.Now.ToLongTimeString(); } private System.Windows.Threading.DispatcherTimer TimerState = new System.Windows.Threading.DispatcherTimer(); TimerState.Tick += new EventHandler(OnTimerDispatcher); TimerState.Interval = TimeSpan.FromSeconds(10); TimerState.Tag = 1; TimerState.Start(); public void OnTimerDispatcher(object sender, EventArgs e) { ((System.Windows.Threading.DispatcherTimer)sender).Stop(); }
// 立即执行,然后在间隔执行 readDataTimer.Tick += new EventHandler(timeCycleRead); // 15秒 readDataTimer.Interval = TimeSpan.FromSeconds(0); public void timeCycleRead(object sender, EventArgs e) { if(readDataTimer.Interval == TimeSpan.FromSeconds(0)) { // 15秒 readDataTimer.Interval = TimeSpan.FromSeconds(15); } //((System.Windows.Threading.DispatcherTimer)sender).Stop(); if (FLAG_REALTIME != (flag & FLAG_REALTIME)) { btnRealtime_Click(null, null); file_index += 1; } else { btnStopRealtime_Click(null, null); } }