C# 中获取时间的方法
直接获取系统当前时间:
<code class="c#">DateTime now = DateTime.Now;</code>
获取特定时间点:
可以使用
DateTime构造函数指定特定日期和时间:
<code class="c#">DateTime specificTime = new DateTime(2023, 12, 25, 12, 00, 00);</code>
获取时间组件:
通过
DateTime类属性可以获取时间组件,例如:
Year
Month
Day
Hour
Minute
Second
示例:
<code class="c#">// 获取当前年月日 int year = now.Year; int month = now.Month; int day = now.Day; // 获取当前小时、分钟、秒 int hour = now.Hour; int minute = now.Minute; int second = now.Second;</code>
格式化时间字符串:
可以使用
ToString方法将时间格式化为字符串:
<code class="c#">// 将时间格式化为 "yyyy-MM-dd HH:mm:ss"
string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");</code>转换时区:
如果需要转换时区,可以使用
TimeZoneInfo类:
<code class="c#">// 获取当前时区
TimeZoneInfo localZone = TimeZoneInfo.Local;
// 将时间转换为指定时区
TimeZoneInfo targetZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime convertedTime = TimeZoneInfo.ConvertTime(now, localZone, targetZone);</code> 