2015-04-22 141 views
2

工作在大型WPF應用程序上,並且存在DateTime格式的一些問題,這是一個巨大的代碼庫,許多地方沒有指定區域性。WPF默認日期時間格式

當用戶在Windows 7或8上打開應用程序時,日期時間格式不同(Win 7使用斜線,Win 8使用破折號)。

我嘗試在應用程序啓動時將文化設置爲「en-US」(請參閱​​下面的鏈接),但它似乎不起作用? Setting Culture (en-IN) Globally in WPF App

如何設置我的WPF應用程序不使用用戶機器的文化?

+0

一定要檢查每個操作系統上的時間/日期格式設置匹配。用戶可以指定他們是否想要破折號或斜槓 - 而且巧合的是,您應該如何格式化日期字符串。我討厭被迫以特定格式讀取日期-_- – Kcvin

+0

這是Windows 8用戶的工作,他們需要進入他們的DateTime設置並添加斜槓而不是破折號。但是我的應用程序總是假設使用斜槓。這是用於UI中的顯示目的,無論代碼是在做什麼DateTime.Now或DateTime.Parse等 – devfunkd

+0

在一個地方的代碼是DateTime.Parse(「2014/05/13」),但解析後的值是不管我提供什麼文化,我都不知道爲什麼。 – devfunkd

回答

2

以下是我在OnStartup使用。它與您使用DefaultThreadCurrentCulture時鏈接的SO問題不同,因爲它爲整個流程和任何啓動的線程設置了默認值。

DefaultThreadCurrentCultureDefaultThreadCurrentUICulture在.NET 4.5及更高...

var newCulture = new CultureInfo(displayCulture); 

// Set desired date format here 
newCulture.DateTimeFormat.ShortDatePattern = "dd MMM yyyy"; 

// You cannot use DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture if 
// you dont have .NET 4.5 or later. Just remove these two lines and pass the culture 
// to any new threads you create and set Thread.CurrentThread... 
CultureInfo.DefaultThreadCurrentCulture = newCulture; 
CultureInfo.DefaultThreadCurrentUICulture = newCulture; 

Thread.CurrentThread.CurrentCulture = newCulture; 
Thread.CurrentThread.CurrentUICulture = newCulture; 

FrameworkElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement), 
    new FrameworkPropertyMetadata(
     System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag))); 
+0

DefaultThreadCurrentCulture不能解決我的問題。 – devfunkd

+0

他們被添加到.net 4.5中,你將不得不使用Thread.CurrentThread,並且在你啓動新的線程時你會仔細地設置它們的文化... – kmcnamee

+0

感謝這解決了它對我來說,我沒有意識到我是在4.0,所以我也在同一時間升級。謝謝! – devfunkd

-1

這會爲你提供你在找什麼,或者你可以使用正則表達式...

DateTime dateTime; 

    bool validDate = DateTime.TryParseExact(
     "04/22/2015", 
     "MM/dd/yyyy", // or you can use MM.dd.yyyy 
     CultureInfo.InvariantCulture, 
     DateTimeStyles.None, 
     out dateTime); 
+0

我需要在全球範圍內設置它,有數百個使用DateTime.Now或DateTime.Parse的代碼庫中出現 – devfunkd

+0

然後創建一個處理它的日期類,我只給了你一段代碼來使用,我不是爲您的工作編寫代碼!你似乎有點批評,就像上面的迴應你抱怨它沒有工作... – TGarrett

+0

問題是關於全球設置,答案並沒有這樣做。我很抱歉發出這樣的聲音,對不起。 – devfunkd