将日期时间转换为字符串“yyyy-mm-dd”

本文关键字:yyyy-mm-dd 字符串 日期 时间 转换 | 更新日期: 2023-09-27 17:50:55

我想知道如何将日期时间转换为字符串值(yyyy-mm-dd)。我有一个控制台应用程序,我希望用户能够将日期写为"yyyy-mm-dd",然后转换为字符串。

我试过这个,但它的工作方向似乎相反。其思想是用户使用Console.ReadLine输入开始日期和结束日期。然后将这些值作为字符串存储在字符串A和B中,以便以后使用。这可能吗?

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

谢谢

将日期时间转换为字符串“yyyy-mm-dd”

你在正确的轨道上,但你有点偏离。例如,在读取

时尝试这样做:
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还是反之亦然。

DateTimeString: just format来源:

 DateTime source = ...;
 String result = source.ToString("yyyy-MM-dd");

StringDateTime:解析精确:

 String source = ...;
 DateTime result = DateTime.ParseExact(source, "yyyy-MM-dd", CultureInfo.InvariantCulture);

或TryParseExact(如果你想检查用户的输入)

 String source = ...;
 DateTime result;
 if (DateTime.TryParseExact(source, "yyyy-MM-dd", 
                            CultureInfo.InvariantCulture, 
                            out result) {
   // parsed
 }
 else {
   // not parsed (incorrect format)
 }

要将DateTime转换为所需(yyyy-mm-dd)格式的字符串值,我们可以这样做:

DateTime testDate = DateTime.Now; //Here is your date field value.
string strdate = testDate.ToString("yyyy, MMMM dd");

虽然可以使用ToString()格式化DateTime值,但不能直接格式化可为空的DateTime (DateTime?)。首先,你必须转换它。((DateTime) someDate) .ToString()。但是,如果变量为空,则需要处理这种情况,否则将抛出异常。DateTime吗?date = null;

if (dateTime != null)
{
    Debug.WriteLine(((DateTime)dateTime).ToString("yyyy-MM-dd"));
}
else
{
    // Handle null date value
    dateTime = DateTime.Now;
    Debug.WriteLine(((DateTime)dateTime).ToString("yyyy-MM-dd"));
}