格式化DateTime.Now到yyyy-mm-dd [英] Format DateTime.Now to yyyy-mm-dd

查看:384
本文介绍了格式化DateTime.Now到yyyy-mm-dd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将DateTime.Now转换为 yyyy-mm-dd 的格式,因为这是我想在查询中使用的唯一格式include。

默认值为 DateTime的格式。现在类似于 5/1/2008 6:32:06 PM

如果我想将其格式更改为 yyyyMMdd 我可以使用以下代码行:

I want to convert the DateTime.Now to the format of yyyy-mm-dd since that is the only format that i can use in my query that i want to include.
The default format of DateTime.Now looks like 5/1/2008 6:32:06 PM.
If i want to change the format of it to yyyyMMdd I could use this line of code:

var dateString1 = DateTime.Now.ToString("yyyyMMdd");

但是,当我为此 yyyy-mm-dd 格式如下:

But, when i try the same for this yyyy-mm-dd format like below:

var dateString2 = DateTime.Now.ToString("yyyy-mm-dd");

我得到的结果是错误的。
对于以下代码行:

the result i get is wrong. For the following lines of code:

var dateString1 = DateTime.Now.ToString("yyyyMMdd");
var dateString2 = DateTime.Now.ToString("yyyy-mm-dd");

Console.WriteLine("yyyyMMdd " + dateString1);
Console.WriteLine("yyyy-mm-dd "+ dateString2);

我得到以下结果:

第二种情况是错误的。

我缺少了什么?

which is wrong for the second case.
What am i missing?

推荐答案

根据 msdn MM 格式说明符代表月份,而 mm -代表分钟。

According to msdn MM format specifier stands for month and mm - for minutes.


mm |分钟,从00到59。

"mm" | The minute, from 00 through 59.

MM |这个月,从01到12。

"MM" | The month, from 01 through 12.

所以您的代码应如下所示:

So your code should look like the following:

    var dateString1 = DateTime.Now.ToString("yyyyMMdd");
    var dateString2 = DateTime.Now.ToString("yyyy-MM-dd");

    Console.WriteLine("yyyyMMdd " + dateString1);
    Console.WriteLine("yyyy-MM-dd "+ dateString2);

您将获得所需的结果

这篇关于格式化DateTime.Now到yyyy-mm-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆