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.Now
returns the time too, I get an error (String was not recognized as a valid DateTime
.) when I try to do the following.
string test = DateTime.ParseExact(DateTime.Now.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
This question is related to
c#
If you need exact your example, you should add format to 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")
Try this:
var mydtn = DateTime.Today;
var myDt = mydtn.Date;return myDt.ToString("d", CultureInfo.GetCultureInfo("en-US"));
Have you tried
DateTime.Now.Date
This should work:
string datetime = DateTime.Today.ToString();
Use the Date property: Gets the date component of this instance.
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;
variable date
contain the date and the time part will be 00:00:00.
or
Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy"));
or
DateTime.ToShortDateString Method-
Console.WriteLine(DateTime.Now.ToShortDateString ());
it should be as simple as
DateTime.Today
String test = DateTime.Now.ToShortDateString();
As mentioned in several answers already that have been already given, you can use 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:
DateTime.Now.ToString("d", CultureInfo.GetCultureInfo("en-US"))
Source: Stackoverflow.com