C# 将日期时间转换为字符串;yyyy-mm-dd“;
我想知道如何将日期时间转换成字符串值(yyyy-mm-dd)。我有一个控制台应用程序,我希望用户能够将日期写为“yyy-mm-dd”,然后将其转换为字符串 我已经试过了,但它似乎是朝着相反的方向工作的。其思想是用户使用Console.ReadLine输入开始日期和结束日期。然后这些值作为字符串存储在字符串A和B中,以后可以使用它们。可能吗C# 将日期时间转换为字符串;yyyy-mm-dd“;,c#,.net,datetime,console-application,converter,C#,.net,Datetime,Console Application,Converter,我想知道如何将日期时间转换成字符串值(yyyy-mm-dd)。我有一个控制台应用程序,我希望用户能够将日期写为“yyy-mm-dd”,然后将其转换为字符串 我已经试过了,但它似乎是朝着相反的方向工作的。其思想是用户使用Console.ReadLine输入开始日期和结束日期。然后这些值作为字符串存储在字符串A和B中,以后可以使用它们。可能吗 string A = string.Empty; string B = string.Empty; DateTime Start = DateTime.Par
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();
谢谢你你走对了方向,但有点偏离了方向。例如,在阅读时尝试以下方法:
var s = Console.ReadLine();
var date = DateTime.ParseExact(s,"yyyy-MM-dd",CultureInfo.InvariantCulture);
您可能还需要使用DateTime.TryParseExact()
,这样更安全,并且您可以处理有人键入垃圾时发生的情况。目前,你会得到一个很好的例外
当输出为特定格式时,您可以使用与DateTime.ToString()
相同的格式,例如:
var date_string = date.ToString("yyyy-MM-dd");
不清楚您想将
DateTime
转换为String
还是反之亦然
从DateTime
到String
:只需格式化源代码:
DateTime source = ...;
String result = source.ToString("yyyy-MM-dd");
从String
到DateTime
:精确解析源代码:
或TryParseExact(如果要检查用户的输入)
要将日期时间转换为所需(yyyy-mm-dd)格式的字符串值,我们可以采用以下方法:
DateTime testDate = DateTime.Now; //Here is your date field value.
string strdate = testDate.ToString("yyyy, MMMM dd");
使用
DateTime.Now.ToString(“yyyy-MM-dd”)
将日期时间转换为字符串。mm
应为大写mm
谢谢!这很有帮助,效果很好。在wich做同样的事情之前,我尝试过这个方法,但在输入时使用了字符串而不是DateTime:Console.WriteLine(“Enter StartDate!(yyyy-mm-dd)”;字符串A=Console.ReadLine();Console.WriteLine(“输入结束日期!(yyyy-mm-dd)”;字符串B=Console.ReadLine();
String source = ...;
DateTime result;
if (DateTime.TryParseExact(source, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
out result) {
// parsed
}
else {
// not parsed (incorrect format)
}
DateTime testDate = DateTime.Now; //Here is your date field value.
string strdate = testDate.ToString("yyyy, MMMM dd");