c#中datetime转换为string怎么实现

c#
561
2024/4/28 19:19:01
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,将DateTime对象转换为字符串可以使用DateTime对象的ToString方法。以下是将DateTime对象转换为字符串的示例代码:

DateTime dateTime = DateTime.Now;
string dateString = dateTime.ToString(); // 默认格式化为 "yyyy-MM-dd HH:mm:ss"
Console.WriteLine(dateString);

如果想要自定义日期时间的格式,可以使用ToString方法的重载版本,传入格式化字符串作为参数,例如:

string customDateString = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(customDateString);

可以根据需要选择合适的格式化字符串来转换DateTime对象为指定格式的字符串。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#遍历字典的方法是什么