关于C#时间和字符串转换的问题

2025-04-24 18:06:42
推荐回答(3个)
回答1:

1、获取当前时间,精确到秒答:DateTime time=DateTime.Now.;

2、将时间转换成字符串形式答:DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
3、再将字符串转回成时间答:DateTime.Parse("2014-01-12").ToString("yyyy-MM-dd");
4、两个时间time1和time2相减,得到一个以秒为 单位的数 答:DateTime dt = DateTime.Now; DateTime nowMonth = dt.AddDays(1 - dt.Day); DateTime endMonth = nowMonth.AddMonths(1).AddDays(-1); TimeSpan ts1 = DateTime.Parse(date) - nowMonth; TimeSpan ts2 = endMonth - DateTime.Parse(date); ts2.Seconds 为秒数

回答2:

获取当前时间,精确到秒
DateTime time=DateTime.Now.;
将时间转换成字符串形式
string timeStr=time.ToString();
再将字符串转回成时间
DateTime time=DateTime.Parse(timeStr);
两个时间time1和time2相减,得到一个以秒为 单位的数TimeSpan tSpan=DateTime.Now -DateTime.Now.AddHours(-1);int secondCount=tSpan.TotalSeconds;

回答3:

1: DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
2: DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
3:DateTime.Parse("2014-01-12").ToString("yyyy-MM-dd");
4:
DateTime dt = DateTime.Now;

DateTime nowMonth = dt.AddDays(1 - dt.Day);
DateTime endMonth = nowMonth.AddMonths(1).AddDays(-1);
TimeSpan ts1 = DateTime.Parse(date) - nowMonth;
TimeSpan ts2 = endMonth - DateTime.Parse(date);
ts2.Seconds 为秒数