using System;
class Program
{
static void Main()
{
// 获取当前时间
DateTime now = DateTime.Now;
Console.WriteLine("当前时间: " + now);
// 获取当前日期
DateTime today = DateTime.Today;
Console.WriteLine("今天是: " + today);
// 添加天数、小时等
DateTime futureDate = now.AddDays(5); // 5天后的时间
Console.WriteLine("5天后的时间: " + futureDate);
// 时间格式化
string formattedDate = now.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine("格式化后的时间: " + formattedDate);
// 计算两个日期之间的差值
TimeSpan difference = futureDate - now;
Console.WriteLine("两个日期之间的差值: " + difference.TotalDays + " 天");
// 解析字符串为DateTime对象
string dateString = "2023-10-01 12:30:45";
DateTime parsedDate = DateTime.Parse(dateString);
Console.WriteLine("解析后的日期: " + parsedDate);
}
}
DateTime.Now
获取当前的日期和时间。DateTime.Today
获取当前的日期(不包含时间部分)。AddDays()
方法可以添加或减少天数,类似地还有 AddHours()
、AddMinutes()
等方法。ToString()
方法并传入格式字符串可以将 DateTime
对象格式化为指定的字符串格式。DateTime
对象之间的时间差,结果是一个 TimeSpan
对象。DateTime
对象:使用 DateTime.Parse()
方法可以将符合格式的字符串解析为 DateTime
对象。希望这些代码和解释对你有帮助!
上一篇:c#分割字符串
下一篇:c# list 转string
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站