卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64336本站已运行4115

c#如何获取时间

c# 获取时间的常见方法包括:获取当前系统时间:datetime now = datetime.now;获取特定时间点:datetime specifictime = new datetime(2023, 12, 25, 12, 00, 00);获取时间组件:yearmonthdayhourminutesecond;格式化时间字符串:now.tostring("yyyy-mm-dd hh:mm:ss");转换时区:timezoneinfo.converttime(now, localzone,

c#如何获取时间

C# 中获取时间的方法

直接获取系统当前时间:

DateTime now = DateTime.Now;

获取特定时间点:

可以使用 DateTime 构造函数指定特定日期和时间:

DateTime specificTime = new DateTime(2023, 12, 25, 12, 00, 00);

获取时间组件:

通过 DateTime 类属性可以获取时间组件,例如:

  • Year
  • Month
  • Day
  • Hour
  • Minute
  • Second

示例:

// 获取当前年月日
int year = now.Year;
int month = now.Month;
int day = now.Day;

// 获取当前小时、分钟、秒
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;

格式化时间字符串:

可以使用 ToString 方法将时间格式化为字符串:

// 将时间格式化为 "yyyy-MM-dd HH:mm:ss"
string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");

转换时区:

如果需要转换时区,可以使用 TimeZoneInfo 类:

// 获取当前时区
TimeZoneInfo localZone = TimeZoneInfo.Local;

// 将时间转换为指定时区
TimeZoneInfo targetZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime convertedTime = TimeZoneInfo.ConvertTime(now, localZone, targetZone);
卓越飞翔博客
上一篇: c#如何调用非静态方法
下一篇: C++ 框架中内存对齐的影响和优化技巧
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏