C# DateTime.ToString问题

C# DateTime.ToString问题,c#,.net,datetime,tostring,C#,.net,Datetime,Tostring,我尝试用“常规日期短时间”格式显示DateTime。 当我使用g说明符时,它会给出类似01-08-13 10:12:00 10:12的内容,而不是01-05-13 10:12 它似乎重复了时间,我不知道为什么 有人吗 编辑1 以下是我使用的代码: var startDate = DateTime.MinValue.ToString("g"); if (Airspace.StartDate != null) startDate = ((DateTime)Airspace.Start

我尝试用“常规日期短时间”格式显示
DateTime
。 当我使用
g
说明符时,它会给出类似
01-08-13 10:12:00 10:12
的内容,而不是
01-05-13 10:12

它似乎重复了时间,我不知道为什么

有人吗

编辑1 以下是我使用的代码:

var startDate = DateTime.MinValue.ToString("g");  
if (Airspace.StartDate != null)  
    startDate = ((DateTime)Airspace.StartDate).ToString("g"); //01-08-13 00:00:00 00:00
编辑2 当我使用“短日期模式”时也会出现同样的问题:


这没有道理

希望这能帮助您:

  DateTime today = DateTime.Now;
  Console.WriteLine(today.ToString("dd-MM-yy H:mm"));
  //Result: 01-08-13 04:33
  Console.ReadLine();
其他格式:

试试这个

  startDate = DateTime.Now.ToString(System.Globalization.CultureInfo.
    CurrentCulture.DateTimeFormat);
“d”格式说明符应用短日期模式,“g”是短日期和短时间模式的串联。所以根据你的结果,你不知何故有了一个包含时间成分的短日期模式。我可以通过明确设置这样一个短的日期模式来重现您的结果,如下所示:

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(DateTime.Today.ToString("g")); // 2008-05-11 00:00:00 00:00
Console.WriteLine(DateTime.Today.ToString("d")); // 2008-05-11 00:00:00
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)
    .OrderByDescending(c => c.DateTimeFormat.ShortDatePattern.Length))
{
    Console.WriteLine($"{culture.Name}   {culture.DateTimeFormat.ShortDatePattern}");
}
我认为真正的问题是,你是如何在一些看起来非常奇怪的文化背景下结束的!我尝试列举一组受支持的区域性,并寻找其短日期格式包含时间说明符的区域性,如下所示:

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(DateTime.Today.ToString("g")); // 2008-05-11 00:00:00 00:00
Console.WriteLine(DateTime.Today.ToString("d")); // 2008-05-11 00:00:00
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)
    .OrderByDescending(c => c.DateTimeFormat.ShortDatePattern.Length))
{
    Console.WriteLine($"{culture.Name}   {culture.DateTimeFormat.ShortDatePattern}");
}

但在几百种文化中,我什么也没想到。那么,您能在代码中的任何地方找到构建
CultureInfo
对象并将其指定为当前区域性的内容吗?如果是,可能代码中的某个地方有错误。

我使用的是C语言和.net Framework 4.0。请将代码中执行此操作的部分张贴出来。问题没有足够的信息。您的代码中一定有内容。顺便提一下,这里有一个很好的参考:Does.toShortDateString,不起作用吗?@LouisvanTonder,不起作用。它没有提供所需的格式,并且仍然在末尾添加
00:00:00
。此解决方案可行,但格式需要区分区域性。我相信
-
将被
/
取代,这取决于文化背景,但这还不够。@Laurent因为你是对的,解决这个问题的方法是硬编码格式
.ToString(“yyyy'-'MM'-'dd”)
注意,如果这是一个要求,那么“-”现在是如何“硬编码的”?我最终使用了这个解决方案。同样的结果,仍然有那些恼人的
00:00