错误:字符串未被识别为有效的DateTime。

时间:2011-11-28 10:53:29

标签: c# linq-to-entities

错误:字符串未被识别为有效的DateTime。 下面是堆栈跟踪 -

  

“在System.DateTimeParse.Parse(String s,DateTimeFormatInfo dtfi,   SystemTime上的DateTimeStyles样式)\ r \ n在System.Convert.ToDateTime(String   价值)\ r \ n at   ConsoleApplication10.Program.b_ 1(<> f _AnonymousType0 1 a) in C:\\Documents and Settings\\xxxxdev\\My Documents\\Visual Studio 2008\\Projects\\ConsoleApplication10\\ConsoleApplication10\\Program.cs:line 23\r\n at System.Linq.Enumerable.WhereSelectListIterator 2.MoveNext()\ r \ n at   C:\ Documents和中的ConsoleApplication10.Program.Main(String [] args)   Settings \ hj81dev \ My Documents \ Visual Studio   2008 \项目\ ConsoleApplication10 \ ConsoleApplication10 \的Program.cs:行   28 \ r \ n在System.AppDomain._nExecuteAssembly(程序集,   System.AppDomain.ExecuteAssembly(String,String [] args)\ r \ n   assemblyFile,Evidence assemblySecurity,String [] args)\ r \ n at   Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly(个)\ r \ n   在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)\ r \ n   在System.Threading.ExecutionContext.Run(ExecutionContext   executionContext,ContextCallback回调,对象状态)\ r \ n at   System.Threading.ThreadHelper.ThreadStart()“

这是我的代码。在sql server数据库中,我的dateofbirth字段是varbinary类型

class Program
    {
        static void Main(string[] args)
        {
            var customerProfileGuid = new Guid("35D02589-C5FA-437D-B661-000215C68584");
            using (CustomerProfileEntities context = new CustomerProfileEntities())
            {
                var test = from x in context.CustomerProfile
                           where x.CustomerProfileId == customerProfileGuid
                           select new { x };

                var customerData = test.ToList();
                var customerResult = (from a in customerData
                                      select new Profile
                                      {
                                          DateOfBirth =Convert.ToDateTime(Encoding.UTF8.GetString(a.x.DateOfBirth)) //getting error here
                                      });

                foreach (var profile in customerResult)
                {
                    var profileData = profile;
                }
            }

        }
    }
    public class Profile
    {
        private DateTime dateOfBirthField;

        [System.Xml.Serialization.XmlElementAttribute(DataType = "date")]
        public DateTime DateOfBirth
        {
            get
            {
                return this.dateOfBirthField;
            }
            set
            {
                this.dateOfBirthField = value;
            }
        }
    }

请做必要的

1 个答案:

答案 0 :(得分:0)

设置cultureinfo以确定使用哪种格式

var cultureInfo = new CultureInfo(yourCulture);
Thread.CurrentThread.CurrentCulture = cultureInfo;