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
You're on the right track but you're a little off. For example try something like this when reading in:
var s = Console.ReadLine();
var date = DateTime.ParseExact(s,"yyyy-MM-dd",CultureInfo.InvariantCulture);
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:
var date_string = date.ToString("yyyy-MM-dd");
It's unclear do you want transform DateTime
to String
or vice versa.
From DateTime
to String
: just format the source:
DateTime source = ...;
String result = source.ToString("yyyy-MM-dd");
From String
to DateTime
: parse the source exact:
String source = ...;
DateTime result = DateTime.ParseExact(source, "yyyy-MM-dd", CultureInfo.InvariantCulture);
or TryParseExact (if you want to check user's input)
String source = ...;
DateTime result;
if (DateTime.TryParseExact(source, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
out result) {
// parsed
}
else {
// not parsed (incorrect format)
}
For converting a DateTime to a string value in required (yyyy-mm-dd) format, we can do this way:
DateTime testDate = DateTime.Now; //Here is your date field value.
string strdate = testDate.ToString("yyyy, MMMM dd");