Professional Documents
Culture Documents
title: csharp-日期时间
date: 2020-06-19 11:44:10
tags: csharp
categories: Language
---
## 字符串转时间
```c#
var dateTime = DateTime.ParseExact("2020/1/4 16:54", "yyyy/M/d HH:mm", null);
var strDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
}
```
<!-- more -->
## 获取时间
```c#
/获取日期+时间
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.ToString("hh:mm:ss"); // 08:05:57
DateTime.Now.TimeOfDay.ToString(); // 20:33:50.7187500
//其他
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
//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 分
```
## 函数执行时间
```c#
static void SubTest()
{
DateTime beforDT = System.DateTime.Now;
//耗时巨大的代码
//耗时巨大的代码
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
```c#
//实例化 Timer 类,设置间隔时间为 10000 毫秒;
System.Timers.Timer t = new System.Timers.Timer(10000);
//到达时间的时候执行事件;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
//设置是执行一次(false)还是一直执行(true);
t.AutoReset = true;
}
```
### Threading.Timer
```c#
private System.Threading.Timer timerClose;
timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 5000,
0);
```c#
public System.Windows.Threading.DispatcherTimer readDataTimer = new
System.Windows.Threading.DispatcherTimer();
readDataTimer.Tick += new EventHandler(timeCycle);
// 秒 毫秒 new TimeSpan(0, 0, 0, 0, millisecondTimeout)
readDataTimer.Interval = TimeSpan.FromSeconds(10);
readDataTimer.Start();