将DateTime转换为字符串“yyyy-mm-dd” [英] Convert DateTime to string "yyyy-mm-dd"
问题描述
我想知道如何将DateTime转换为字符串值(yyyy-mm-dd)。我有一个控制台应用程序,我希望用户能够写一个日期为yyyy-mm-dd,然后转换为字符串。
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.
我有尝试了这个,但它似乎在相反的方向工作。这个想法是用户通过Console.ReadLine输入开始日期和结束日期。然后,这些值作为字符串存储在字符串A和B中,然后可以稍后使用。这是可能吗?
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();
谢谢
推荐答案
你在正确的轨道上,但你有点偏离。例如,在阅读时尝试这样的事情:
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);
您可能需要使用 DateTime.TryParseExact()
以及它有点安全,你可以处理当有人输入垃圾时会发生什么。现在你会得到一个很好的例外。
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.
当输出以特定格式,您可以使用与 DateTime.ToString()
相同的格式,例如:
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");
这篇关于将DateTime转换为字符串“yyyy-mm-dd”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!