Im wondering how to convert a DateTime to a string value (yyyy-mm-dd). I have a console application and i want the user to be able to write a Date as "yyyy-mm-dd" which are then converted as a string.
I have tried this but it works in oposite direction it seem. The idea is that the user enters a Start date and an End date with Console.ReadLine. Then these values are stored as strings in string A and B wich could then be used later. Is that possible?
string A = string.Empty;
string B = string.Empty;
DateTime Start = DateTime.ParseExact(A, "yyyy-mm-dd",CultureInfo.InvariantCulture);
Console.WriteLine("Enter StartDate! (yyyy-mm-dd)");
Start = Console.ReadLine();
DateTime End = DateTime.ParseExact(A, "yyyy-mm-dd",CultureInfo.InvariantCulture);
Console.WriteLine("Enter EndDate! (yyyy-mm-dd)");
End = Console.ReadLine();
Thank you
It's unclear do you want transform
DateTime
toString
or vice versa.From
DateTime
toString
: just format the source:From
String
toDateTime
: parse the source exact:or TryParseExact (if you want to check user's input)
You're on the right track but you're a little off. For example try something like this when reading in:
You might want to use
DateTime.TryParseExact()
as well, it's a bit safer and you can handle what happens when someone types garbage in. As it stands you'll get a nice exception currently.When outputting to a specific format you can use the same format with
DateTime.ToString()
, for example:For converting a DateTime to a string value in required (yyyy-mm-dd) format, we can do this way: