Web服务 - 日期时间错误

时间:2018-04-17 21:40:00

标签: c# sql asp.net datetime type-conversion

我正在尝试检查我的网络服务是否运行良好。所有其他的都可以,但每当我运行这个特定的一个我得到一个错误。在我的数据库中,DateOfBirth的数据类型是' datetime'对于DateApplied也是' datetime'。但每当我想在我的浏览器上检查它是否有效时我会收到此错误消息:

System.FormatException: The string was not recognized as a valid DateTime.
There is an unknown word starting at index 0.
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.Convert.ToDateTime(String value)
   at FinalService.getfinal() in c:\Users\Daniel\Documents\Visual Studio 2012\WebSites\DevinApp\App_Code\FinalService.cs:line 26

以下是我的代码:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
public class FinalService : System.Web.Services.WebService 
    {
        [WebMethod]
        public void getfinal()
        {
            var cs = ConfigurationManager.ConnectionStrings["NNPC-ChevronScholarshipConnectionString"].ConnectionString;
            var students = new List<Final>();
            using (var con = new SqlConnection(cs))
            {
                var cmd = new SqlCommand("getapplicants", con) { CommandType = CommandType.StoredProcedure };
                con.Open();
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var student = new Final
                    {
                        ID = Convert.ToInt32(dr[0].ToString()),
                        ApplicationID = dr[1].ToString(),
                        FirstName = dr[2].ToString(),
                        MiddleName = dr[3].ToString(),
                        LastName = dr[4].ToString(),
                        DateOfBirth = Convert.ToDateTime(dr[5].ToString()),

                        Gender = dr[6].ToString(),
                        Phone = dr[7].ToString(),
                        Email = dr[8].ToString(),
                        DateApplied = Convert.ToDateTime(dr[9].ToString()),
                        CurrentLevel = dr[10].ToString(),
                        MatricNo = dr[11].ToString()

                    };
                    students.Add(student);
                }
            }
            var js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(students));
        }

}

1 个答案:

答案 0 :(得分:2)

这意味着dr[5].ToString()返回的is不是有效的DateTime。它遇到了#0;索引0和#34的未知单词; - 这意味着字符串的第一个字符对DateTime s无效。

我会在数据库的该列中查找错误的数据。

编辑:

此外,没有必要转换为字符串。您可以直接从SQL DateTime转换为C#DateTime。与此非常相似的东西应该有效:

 dr.GetDateTime(5);