代码之家  ›  专栏  ›  技术社区  ›  Matthew Hood

设置默认日期时间格式C#

  •  32
  • Matthew Hood  · 技术社区  · 15 年前

    是否有方法设置或重写整个应用程序的默认日期时间格式。我正在用C.NET MVC 1.0编写一个应用程序,并使用大量的泛型和反射。如果我可以将默认的datetime.toString()格式重写为“dd-mmm-yyyy”,那就简单多了。我不希望在其他计算机上运行站点时更改此格式。

    编辑- 只是澄清一下,我的意思是专门调用ToString,而不是其他扩展函数,这是因为反射/生成的代码。只需更改ToString输出就更容易了。

    6 回复  |  直到 10 年前
        1
  •  48
  •   Community CDub    13 年前

    日期时间的“默认格式”是:

    ShortDatePattern + ' ' + LongTimePattern
    

    至少在当前 mono implementation . 如果您希望显示2001-02-03T04:05:06Z之类的内容,即按照中指定的日期和时间组合,则这会特别痛苦。 ISO 8606 但在您的案例中不是一个大问题:

    using System;
    using System.Globalization;
    using System.Threading;
    
    namespace test {
        public static class Program {
            public static void Main() {
                CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                culture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
                culture.DateTimeFormat.LongTimePattern = "";
                Thread.CurrentThread.CurrentCulture = culture;
                Console.WriteLine(DateTime.Now);
            }
        }
    }
    

    这将设置ToString on DateTimes的默认行为,以返回预期的格式。

        2
  •  8
  •   Seb Nilsson    15 年前

    它取决于应用程序的本地化设置。 Change that accordingly 以获得正确的格式。

    否则就有一个助手类或一个始终处理日期时间的扩展方法。

    public static string ToMyDateTime(this DateTime dateTime) {
        return dateTime.ToString("dd-MMMM-yy");
    }
    
        3
  •  1
  •   Tadas Å ukys    15 年前

    DateTime.ToString() 组合由的shortdatepattern和longtimepattern属性返回的自定义格式字符串 DateTimeFormatInfo .您可以在中指定这些模式 DateTimeFormatInfo.CurrentInfo .

    我从未试过这样做。

        4
  •  1
  •   Bjorn Bailleul    15 年前

    如果你想确保你的文化保持不变,那就自己设置它来避免麻烦。

    System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("nl-BE");
    System.Threading.Thread.CurrentThread.CurrentCulture = ci;
    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    

    上面的示例将线程的文化设置为比利时荷兰语。

    currentCulture执行所有日期和时间处理,currentUICulture处理UI本地化(如资源)。

        5
  •  0
  •   ema    15 年前

    您可以编写这样的扩展方法:

    public static string ToMyString(this DateTime dateTime)
    {
      return dateTime.ToString("needed format");
    }
    
        6
  •  0
  •   Fernando    15 年前

    我不确定这是否适用于Web应用,但您可以尝试设置 DateTimeFormat 当前区域性的属性。

    检查 this 特别地 this .