Convert DateTime to string “yyyy-mm-dd”

荒凉一梦 提交于 2019-12-13 09:33:18

问题


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


回答1:


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");



回答2:


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)
 }



回答3:


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");


来源:https://stackoverflow.com/questions/22477356/convert-datetime-to-string-yyyy-mm-dd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!