Convert DateTime to string “yyyy-mm-dd”

2019-09-21 10:15发布

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

3条回答
2楼-- · 2019-09-21 10:40

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)
 }
查看更多
forever°为你锁心
3楼-- · 2019-09-21 10:45

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");
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-09-21 10:45

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");
查看更多
登录 后发表回答