C# 时间与日期

下面介绍C#生成日期与时间的方法

 

//获取当前时间
DateTime now = DateTime.Now;
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;

//DateTime 转换 string
string dateTime1 = now.ToString("yyyy-MM-dd HH:mm:ss");

//string 转换 DateTime
DateTime dateTime2 = DateTime.ParseExact("2021-10-30 18:02:00");

//时间戳生成
DateTimeOffset dto = new DateTimeOffset(now);
long seconds = dto.ToUnixTimeSeconds();//
long milli = dto.ToUnixTimeMilliseconds();//毫秒

//时间戳转换成时间
DateTime dateTime3 = DateTimeOffset.FromUnixTimeSeconds(seconds).ToLocalTime().DateTime;//秒级时间戳转换时间
DateTime dateTime4 = DateTimeOffset.FromUnixTimeMilliseconds(milli).ToLocalTime().DateTime; //毫秒级时间戳转换时间

 

posted @ 2021-10-30 18:22  Zeng。  阅读(1034)  评论(0编辑  收藏  举报