You are on page 1of 4

---

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");

string strFormat = "yyyy/M/d HH:mm";


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("数据日期格式不支持,请联系技术支持");
}

}
```
<!-- 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

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 分
```

## 函数执行时间

```c#
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);
}

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 之间

```c#
//实例化 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

```c#
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
专门设计的,不然的话会提示界面资源被其他线程所拥有而无法更新界面。

```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();

public void timeCycle(object sender, EventArgs e)


{
((System.Windows.Threading.DispatcherTimer)sender).Stop();
}
```

You might also like