C# 没有时间的当前日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13178752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:43:08  来源:igfitidea点击:

Current date without time

c#

提问by Rocshy

How can I get the current date but without the time? I am trying to convert the date from the "dd.mm.yyyy" format to "yyyy-MM-dd", because DateTime.Nowreturns the time too, I get an error (String was not recognized as a valid DateTime.) when I try to do the following.

如何获取当前日期但没有时间?我正在尝试将日期从“dd.mm.yyyy”格式转换为“yyyy-MM-dd”,因为DateTime.Now也会返回时间,String was not recognized as a valid DateTime当我尝试执行以下操作时出现错误 ( .)。

string test = DateTime.ParseExact(DateTime.Now.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

采纳答案by Danilo Vulovi?

String test = DateTime.Now.ToString("dd.MM.yyy");

回答by mhttk

Have you tried

你有没有尝试过

DateTime.Now.Date

回答by Pranay Rana

Use the Dateproperty: Gets the date component of this instance.

使用Date属性:获取此实例的日期组件。

var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;

variable datecontain the date and the time part will be 00:00:00.

变量date包含日期,时间部分将为 00:00:00。

or

或者

Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy"));

or

或者

DateTime.ToShortDateString Method-

DateTime.ToShortDateString 方法-

Console.WriteLine(DateTime.Now.ToShortDateString ());

回答by Frank59

String test = DateTime.Now.ToShortDateString();

回答by Uriil

If you need exact your example, you should add format to ToString()

如果您需要确切的示例,则应向 ToString() 添加格式

    string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

But it's better to use straight formatting:

但最好使用直接格式:

    string test = DateTime.Now.ToString("yyyy-MM-dd")

回答by Waqas

it should be as simple as

它应该像

DateTime.Today

回答by PierrOz

As mentioned in several answers already that have been already given, you can use ToShorDateString():

正如已经给出的几个答案中所述,您可以使用ToShorDateString()

DateTime.Now.ToShortDateString();

However, you may be a bit blocked if you also want to use the culture as a parameter. In this case you can use the ToString()method with the "d"format:

但是,如果您还想使用文化作为参数,您可能会有点受阻。在这种情况下,您可以使用ToString()以下"d"格式的方法:

DateTime.Now.ToString("d", CultureInfo.GetCultureInfo("en-US"))

回答by John Farragher

Try this:

尝试这个:

   var mydtn = DateTime.Today;
   var myDt = mydtn.Date;return myDt.ToString("d", CultureInfo.GetCultureInfo("en-US"));

回答by MIchael Louw

This should work:

这应该有效:

string datetime = DateTime.Today.ToString();