设置默认日期时间格式C# [英] Set Default DateTime Format c#

查看:1402
本文介绍了设置默认日期时间格式C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有设定或覆盖默认DateTime格式为整个应用程序的方式。我写在C#.NET MVC 1.0的应用程序和使用泛型和反射很多。就会简单得多,如果我可以覆盖默认则DateTime.ToString()格式是DD-MMM-YYYY。我不希望这种格式时,该网站是在不同的机器上运行的改变。

Is there a way of setting or overriding the default DateTime format for an entire application. I am writing an app in C# .Net MVC 1.0 and use alot of generics and reflection. Would be much simpler if I could override the default DateTime.ToString() format to be "dd-MMM-yyyy". I do not want this format to change when the site is run on a different machine.

编辑 -
只是为了澄清我的意思是专门调用toString,而不是一些其他的扩展功能,这是因为反射/生成code的。会更容易只是改变的ToString输出。

Edit - Just to clarify I mean specifically calling the ToString, not some other extension function, this is because of the reflection / generated code. Would be easier to just change the ToString output.

推荐答案

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

The "default format" of a datetime is:

ShortDatePattern + ' ' + LongTimePattern

至少在当前单实施
这是情况特别痛苦要显示类似2001-02-03T04:05:06Z即如 ISO 8606 ,但不是在你的情况下,一个很大的问题:

at least in the current mono implementation. This is particularly painful in case you want to display something like 2001-02-03T04:05:06Z i.e. the date and time combined as specified in ISO 8606, but not a big problem in your case:

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的默认行为上的日期时间,返回你所期望的格式。

This will set the default behavior of ToString on datetimes to return the format you expect.

这篇关于设置默认日期时间格式C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆