简体   繁体   English

如何在Visual Studio 2017中的C#Razor中获取当前日期

[英]How to get current date in C# Razor in Visual Studio 2017

I've got some C# Razor code that is supposed to generate the current date and format it into the following string format - yyyy-mm-dd . 我有一些C# Razor代码,可以生成当前日期并将其格式化为以下字符串格式yyyy-mm-dd It doesn't seem to be working with the code I'm using. 它似乎不适用于我正在使用的代码。 I'm getting 2001-01-02 instead of the current date. 我正在获取2001-01-02而不是当前日期。 I'm not sure what I'm doing wrong here. 我不确定我在做什么错。 Doesn't the DateTime() give the current date by default? 默认情况下, DateTime()是否提供当前日期吗?

var today = new DateTime();
var dd = today.Date.Day;

var mm = today.Month + 1;
var yyyy = today.Year;

var yyyy_string = yyyy.ToString();
var mm_string = mm.ToString();
var dd_string = dd.ToString();

if (dd < 10)
{
    dd_string = '0' + dd_string;
}

if (mm < 10)
{
    mm_string = '0' + mm_string;
}
var today_string = yyyy_string + '-' + mm_string + '-' + dd_string;

You can get the formatted current date plus one month with 您可以通过以下方式获取格式化的当前日期加上一个月:

string today_string = DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd");

Outputs something like "2019-07-27" where month and day have always two digits. 输出类似"2019-07-27" ,其中月和日始终为两位数。

Note that the format "yyyy-Md" would produce months and days with one digit for numbers < 10. 请注意,格式"yyyy-Md"将产生月和日,其中数字<10的数字为一位。

The static property DateTime.Now yields the current date and time. 静态属性DateTime.Now产生当前日期和时间。 We could also use DateTime.Date to strip off the time part, but this is not necessary, as we specify the desired format in ToString . 我们还可以使用DateTime.Date剥离时间部分,但这不是必需的,因为我们在ToString指定了所需的格式。

You are adding 1 to the month number. 您要在月份数上加1。 This is wrong, as in December, you would get 13. Also, at the 31st of a month (eg Jan 31) you would get Feb 31 as a result. 这是错误的,因为在12月您将获得13。此外,在一个月的31号(例如1月31日),您将得到2月31日。 So, it is better to add 1 month to the whole date with .AddMonths(1) . 因此,最好使用.AddMonths(1)在整个日期中添加1个月。 This method takes care to produce a valid date. 此方法要注意产生一个有效的日期。

Can't you just use DateTime.Now?; 您不能只使用DateTime.Now吗?

    var today = DateTime.Now;
    var dd = today.Date.Day;

    var mm = today.Month + 1;
    var yyyy = today.Year;

    var yyyy_string = yyyy.ToString();
    var mm_string = mm.ToString();
    var dd_string = dd.ToString();

    if (dd < 10)
    {
        dd_string = '0' + dd_string;
    }

    if (mm < 10)
    {
        mm_string = '0' + mm_string;
    }
    var today_string = yyyy_string + '-' + mm_string + '-' + 
    dd_string;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM