[英]String was not recognized as a valid DateTime when machine time format is changed.
我有一個格式為dd/MM/yyyy
的Date字符串,我是要以'yyyyMMdd'形式獲取此字符串的字符串,所以我嘗試了:
todate1 = Convert.ToDateTime(txttdate.Text).ToString("yyyyMMdd")
當我的本地機器時間格式為dd/MM/yyyy
時,它工作正常,但是當我更改系統時間格式時,它停止工作,這給了我錯誤
String was not recognized as a valid DateTime
如何解決這個問題? 我需要將dd/MM/yyyy
字符串轉換為yyyyMMdd
使用DateTime.ParseExact
而不是Convert.ToDateTime
並指定模式和InvariantCulture
作為格式提供者:
var todate1 = DateTime.ParseExact(@"05/12/2013", @"dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyyMMdd");
這樣可以防止您的代碼在不同的區域性設置下失敗。
使用ParseExact
並指定CultureInfo.InvariantCulture
:
DateTime todate1;
if (DateTime.TryParseExact(txttdate.Text, new[] { "dd/MM/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out todate1)) {
string yourNewFormat = todate1.ToString("yyyyMMdd");
}
else {
// it failed
}
使用TryParseExact
可使您從提供的潛在無效日期中恢復。
我在Web應用程序中遇到了類似的問題,嘗試了上述類似的許多操作,但沒有任何幫助。 但是,當我在配置文件中添加全球化標記時,它就像一個符咒。
<system.web>
<globalization requestEncoding="UTF-8" responseEncoding="UTF-8" uiCulture="en-GB" culture="en-GB" />
</system.web>
將文化更改為美國或印度或您想要的任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.