Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 时间格式是24小时格式吗?_C#_Datetime_String.format - Fatal编程技术网

C# 时间格式是24小时格式吗?

C# 时间格式是24小时格式吗?,c#,datetime,string.format,C#,Datetime,String.format,我得到一个以字符串形式传递给我的时间格式字符串。它可以是像“t”这样的标准字符串,但也可以是自定义字符串(包含“HH”等)。我怎样才能知道,如果显示,它将是12小时或24小时格式?(取决于区域性和所有内容…步骤1:如有必要,将标准格式字符串转换为选定区域性的等效自定义格式字符串。这使用反射逻辑来模拟DateTime.ToString if (formatString.Length == 1) { // Get formatter for the culture of yo

我得到一个以字符串形式传递给我的时间格式字符串。它可以是像“t”这样的标准字符串,但也可以是自定义字符串(包含“HH”等)。我怎样才能知道,如果显示,它将是12小时或24小时格式?(取决于区域性和所有内容…

步骤1:如有必要,将标准格式字符串转换为选定区域性的等效自定义格式字符串。这使用反射逻辑来模拟
DateTime.ToString

if (formatString.Length == 1)
{        
    // Get formatter for the culture of your choice - e.g. the current culture
    DateTimeFormatInfo fi = CultureInfo.CurrentCulture.DateTimeFormat;

    formatString = epf.Invoke(
        null,
        new object[]{
            formatString,
            DateTime.MinValue,
            fi,
            TimeSpan.MinValue});
}
第2步:解析字符串以查看它是否包含12小时或24小时说明符。这是一种不幸的混合,使用反射逻辑尽可能地模拟
DateTime.ToString
,在不可能的情况下使用自定义逻辑,但它似乎工作正常

for (int i = 0; i < formatString.Length; i++)
{
    char current = formatString[i];
    if (current == '"' || current == '\'') // Skip literal quoted sections
    {
        i += (int)pqs.Invoke(
            null,
            new object[] {
                formatString,
                i,
                new StringBuilder()});
    }
    else if (current == '\\') // Skip escaped characters
    {
        i+= 1;
    }
    else if (current == 'h')
    {
        is12Hour = true;
    }
    else if (current == 'H')
    {
        is24Hour = true;
    }
}

第一个处理将给定区域性的单字符标准格式说明符转换为多字符自定义格式说明符。第二个处理自定义格式说明符内的引用文字。

步骤1:如果需要,将标准格式字符串转换为所选区域性的等效自定义格式字符串。这使用反射逻辑来模拟
DateTime.ToString

if (formatString.Length == 1)
{        
    // Get formatter for the culture of your choice - e.g. the current culture
    DateTimeFormatInfo fi = CultureInfo.CurrentCulture.DateTimeFormat;

    formatString = epf.Invoke(
        null,
        new object[]{
            formatString,
            DateTime.MinValue,
            fi,
            TimeSpan.MinValue});
}
第2步:解析字符串以查看它是否包含12小时或24小时说明符。这是一种不幸的混合,使用反射逻辑尽可能地模拟
DateTime.ToString
,在不可能的情况下使用自定义逻辑,但它似乎工作正常

for (int i = 0; i < formatString.Length; i++)
{
    char current = formatString[i];
    if (current == '"' || current == '\'') // Skip literal quoted sections
    {
        i += (int)pqs.Invoke(
            null,
            new object[] {
                formatString,
                i,
                new StringBuilder()});
    }
    else if (current == '\\') // Skip escaped characters
    {
        i+= 1;
    }
    else if (current == 'h')
    {
        is12Hour = true;
    }
    else if (current == 'H')
    {
        is24Hour = true;
    }
}

第一个处理将给定区域性的单字符标准格式说明符转换为多字符自定义格式说明符。第二个处理自定义格式说明符内的引用文本。

您可以使用字符串格式化已知日期,如果使用24小时时间,您知道该字符串将仅包含特定值:

if ((new DateTime(1, 1, 1, 23, 1, 1)).ToString(formatString).Contains("23"))
    Console.WriteLine("24");
else
    Console.WriteLine("12");

您可以使用字符串设置已知日期的格式,如果该字符串使用24小时时间,则您知道该字符串将仅包含特定值:

if ((new DateTime(1, 1, 1, 23, 1, 1)).ToString(formatString).Contains("23"))
    Console.WriteLine("24");
else
    Console.WriteLine("12");

最简单的方法是尝试一个日期,然后检查字符串中的给定数字,这是您唯一希望的方法。例如,
2000-01-01T19:00:00Z
是否导致包含
7
9
或两者的字符串

要确定的是,即使面对像
“‘此有效字符串将使您陷入困境’”这样的奇怪字符串,您也需要在获得给定区域性信息的完整版本(如果需要)后检查该字符串

作为
CultureInfo
DateTimeFormatInfo
上的扩展方法,以下内容也很有意义

实际上,您可以通过将通常只包含日期信息的标准格式放入立即返回
None
的组中来简化,但我决定抓住其中的奇怪之处:

[Flags]
public enum HourRepType
{
  None = 0,
  Twelve = 1,
  TwentyFour = 2,
  Both = Twelve | TwentyFour
}
public static HourRepType FormatStringHourType(string format, CultureInfo culture = null)
{
  if(string.IsNullOrEmpty(format))
    format = "G";//null or empty is treated as general, long time.
  if(culture == null)
    culture = CultureInfo.CurrentCulture;//allow null as a shortcut for this
  if(format.Length == 1)
    switch(format)
    {
      case "O": case "o": case "R": case "r": case "s": case "u":
        return HourRepType.TwentyFour;//always the case for these formats.
      case "m": case "M": case "y": case "Y":
        return HourRepType.None;//always the case for these formats.
      case "d":
          return CustomFormatStringHourType(culture.DateTimeFormat.ShortDatePattern);
      case "D":
        return CustomFormatStringHourType(culture.DateTimeFormat.LongDatePattern);
      case "f":
        return CustomFormatStringHourType(culture.DateTimeFormat.LongDatePattern + " " + culture.DateTimeFormat.ShortTimePattern);
      case "F":
        return CustomFormatStringHourType(culture.DateTimeFormat.FullDateTimePattern);
      case "g":
        return CustomFormatStringHourType(culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.ShortTimePattern);
      case "G":
        return CustomFormatStringHourType(culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.LongTimePattern);
      case "t":
        return CustomFormatStringHourType(culture.DateTimeFormat.ShortTimePattern);
      case "T":
        return CustomFormatStringHourType(culture.DateTimeFormat.LongTimePattern);
      default:
        throw new FormatException();
    }
  return CustomFormatStringHourType(format);
}
private static HourRepType CustomFormatStringHourType(string format)
{
  format = new Regex(@"('.*')|("".*"")|(\\.)").Replace(format, "");//remove literals
  if(format.Contains("H"))
    return format.Contains("h") ? HourRepType.Both : HourRepType.TwentyFour;
  return  format.Contains("h") ? HourRepType.Twelve : HourRepType.None;
}

最简单的方法是尝试一个日期,然后检查字符串中的给定数字,这是您唯一希望的方法。例如,
2000-01-01T19:00:00Z
是否导致包含
7
9
或两者的字符串

要确定的是,即使面对像
“‘此有效字符串将使您陷入困境’”这样的奇怪字符串,您也需要在获得给定区域性信息的完整版本(如果需要)后检查该字符串

作为
CultureInfo
DateTimeFormatInfo
上的扩展方法,以下内容也很有意义

实际上,您可以通过将通常只包含日期信息的标准格式放入立即返回
None
的组中来简化,但我决定抓住其中的奇怪之处:

[Flags]
public enum HourRepType
{
  None = 0,
  Twelve = 1,
  TwentyFour = 2,
  Both = Twelve | TwentyFour
}
public static HourRepType FormatStringHourType(string format, CultureInfo culture = null)
{
  if(string.IsNullOrEmpty(format))
    format = "G";//null or empty is treated as general, long time.
  if(culture == null)
    culture = CultureInfo.CurrentCulture;//allow null as a shortcut for this
  if(format.Length == 1)
    switch(format)
    {
      case "O": case "o": case "R": case "r": case "s": case "u":
        return HourRepType.TwentyFour;//always the case for these formats.
      case "m": case "M": case "y": case "Y":
        return HourRepType.None;//always the case for these formats.
      case "d":
          return CustomFormatStringHourType(culture.DateTimeFormat.ShortDatePattern);
      case "D":
        return CustomFormatStringHourType(culture.DateTimeFormat.LongDatePattern);
      case "f":
        return CustomFormatStringHourType(culture.DateTimeFormat.LongDatePattern + " " + culture.DateTimeFormat.ShortTimePattern);
      case "F":
        return CustomFormatStringHourType(culture.DateTimeFormat.FullDateTimePattern);
      case "g":
        return CustomFormatStringHourType(culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.ShortTimePattern);
      case "G":
        return CustomFormatStringHourType(culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.LongTimePattern);
      case "t":
        return CustomFormatStringHourType(culture.DateTimeFormat.ShortTimePattern);
      case "T":
        return CustomFormatStringHourType(culture.DateTimeFormat.LongTimePattern);
      default:
        throw new FormatException();
    }
  return CustomFormatStringHourType(format);
}
private static HourRepType CustomFormatStringHourType(string format)
{
  format = new Regex(@"('.*')|("".*"")|(\\.)").Replace(format, "");//remove literals
  if(format.Contains("H"))
    return format.Contains("h") ? HourRepType.Both : HourRepType.TwentyFour;
  return  format.Contains("h") ? HourRepType.Twelve : HourRepType.None;
}


如果它是一个真正自定义的字符串,它甚至可以是两个…@Rawling:它不会是那个自定义的:)如果它是一个真正自定义的字符串,它甚至可以是两个…@Rawling:它不会是那个自定义的:)我更新了这个答案,使用反射来模拟
日期时间。ToString
,而不是尝试自己去做。@Jon该死,你说得对。另外,如果在那里的某个地方有
\h
,如果实现更改为不再使用
ExpandPredefinedFormat
,因为它没有文档记录。关于一个只使用公共文档化方法的问题,请看我的答案。@Jon我想我已经纠正了这个问题,尽管它并不漂亮。也有赖于进一步的反思。。。渴望看到你的公众唯一答案:)它在这页的下面。不能说switch语句在OO语言中非常优雅,但我认为它适用于所有边缘情况。我更新了这个答案,以使用反射来模拟
DateTime.ToString
,而不是自己尝试去做。@Jon该死,你是对的。另外,如果在那里的某个地方有
\h
,如果实现更改为不再使用
ExpandPredefinedFormat
,因为它没有文档记录。关于一个只使用公共文档化方法的问题,请看我的答案。@Jon我想我已经纠正了这个问题,尽管它并不漂亮。也有赖于进一步的反思。。。渴望看到你的公众唯一答案:)它在这页的下面。不能说switch语句在OO语言中是非常优雅的,但我认为它符合所有的边缘情况。缺少可笑的格式字符串(例如,在其中包含一个literal
23
),这是一种很好的简单方法,你可能会进一步强化它,以对抗这种愚蠢行为。@Rawling-yes。自从发布这篇文章以来,我一直在思考是否有一个体面的方法来保护它不受这种输入的影响;从输入字符串中删除任何显式的13-23…@Rawling-如果调用
.ToString(formatString.Replace(“23”),我认为“23”没有任何方法除非是24小时格式,否则将出现在输出中。您还必须小心转义-字符串中可能有
\2\3
,这也会输出
23
,但如果删除
\2\3
,则必须小心第一个“`本身没有转义…缺少可笑的格式字符串(例如,其中包含文字
23
)这是一种很好的简单方法,您可能会