![](/img/trans.png)
[英]Convert date format of string to datetime MM/dd/yyyy when system date formate is dd/MM/yyyy
[英]Why Convert.ChangeType() not converting a date string (in dd/MM/yyyy format) into datetime type?
以下是我打算通過反射填充實體數據的代碼。
public static void SetEntityProperty(object entity, DevExpress.Web.ASPxFormLayout formLayoutControl)
{
if (formLayoutControl != null)
{
Type type = entity.GetType();
System.Reflection.PropertyInfo[] properties = type.GetProperties();
System.Data.DataTable dt = new System.Data.DataTable();
foreach (System.Reflection.PropertyInfo pi in properties)
{
var layoutItem = formLayoutControl.FindItemByFieldName(pi.Name);
if (layoutItem != null && layoutItem.CssClass == "ro-item") continue;
var control = formLayoutControl.FindNestedControlByFieldName(pi.Name);
if (control != null && control is DevExpress.Web.ASPxEdit)
{
var targetType = Data.IsNullableType(pi.PropertyType) ? Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType;
try
{
if ((control as DevExpress.Web.ASPxEdit).Value != null)
{
//here (control as DevExpress.Web.ASPxEdit).Value = "19/05/2015" and control is a read only text box
var value = Convert.ChangeType((control as DevExpress.Web.ASPxEdit).Value, targetType);
if (value != null && value is System.String)
{
value = value.ToString().Trim();
(control as DevExpress.Web.ASPxEdit).Value = value;
}
pi.SetValue(entity, value, null);
}
else
{
pi.SetValue(entity, null, null);
}
}
catch (Exception ex)
{
pi.SetValue(entity, value, null);
}
}
else
throw ex;
}
}
}
我在這里做錯了什么? 我發現與Convert.ChangeType
相關的其他問題很少,但是所有建議已在此代碼中實現。 我正在使用Visual Studio 2013 C#,DevExpress 14.2.6。 請幫忙。 謝謝。
嘗試這個:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace DateTimeConvert
{
class Program
{
static void Main(string[] args)
{
var text1 = "19/05/2015"; //dd/mm/yyyy format
var text2 = "05/19/2015"; //mm/dd/yyyy format
var result = DateTime.Now;
DateTime.TryParse(text1, out result);
Console.WriteLine(result);
DateTime.TryParse(text2, out result);
Console.WriteLine(result);
//Depending on computer's current culture format this will cause an error due to dd/MM/yyyy CULTURE format
//DateTime date = (DateTime)Convert.ChangeType(text1, typeof(DateTime));
var date = DateTime.ParseExact(text1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);
Console.ReadLine();
}
}
}
發生的情況是您正在轉換日期時間格式為“ dd / MM / yyyy”。 取決於您計算機的文化格式。 您可以使用DateTime.ParseExact
指導使用正確的格式CultureInfo.InvariantCulture
。
不要養成吞咽異常的習慣,甚至不要處理您不知道的異常。
在這種情況下,您的應用程序很可能無法解析提供的日期。
不要使用Convert類來解析文本字符串。 改用Parse方法。
var resultDate = DateTime.ParseExact(((Control)DevExpress.Web.ASPxEdit).Value, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.