c# - 无法更改 DateTime 的月份格式

标签 c# datetime

我正在尝试将日期和时间字符串转换为 DateTime 变量,同时将月份更改为两位数月份而不是一位数。

这是我当前的代码:

string date = item; // 6/17/15 10:02:01 AM
DateTime dt = Convert.ToDateTime(item);
string dtm = dt.Month.ToString("MM");
string dty = dt.Year.ToString("yyyy");
Console.WriteLine(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dty, dtm, dt.Day);
Console.WriteLine(dt.TimeOfDay);

最佳答案

你需要:

string dtm = dt.ToString("MM");
string dty = dt.ToString("yyyy");

您的原始代码试图将自定义 DateTime 格式应用于 dt.Month,它只是一个 int,因此自定义日期格式字符串不适用于它。 (今年也是如此)。

关于c# - 无法更改 DateTime 的月份格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115317/

相关文章:

c# - 将 UTC 时间字符串反序列化为本地时间

c# - XPTable 滚动出错

c# - MVC 后模型 - 集合属性没有元素

datetime - 将 DATETIME 转换为人类可读的日期

c# - 了解 float 问题

r - 根据时间在R中绘制数据

ruby-on-rails - 我怎样才能以 ruby 开始当前的工作日?

r - 如何将日期和分钟添加到 R 中的日期时间对象?

python - 更改 matplotlib 中日期时间轴的格式

c# - 统计一个字符串在一个字符串中出现的次数