FormatException错误字符串到DateTime

时间:2017-07-31 13:53:29

标签: c# sql asp.net string datetime

我一直坐在座位上一个多小时不知道错误是什么..有人可以帮忙吗?

Error

错误被称为“当将字符串转换为DateTime时,解析字符串以在将每个变量放入DateTime对象之前获取日期。

字段名称“LastLoginTime”是我数据库中的DATETIME数据类型。

这些是代码..

protected void Page_Load(object sender, EventArgs e)
{
    AuditNLoggingDAO al = new AuditNLoggingDAO();

    int result = 0;

    int resultLogout = 0;

    DateTime dateTimeOfLatestLogin = DateTime.MinValue;

    //Get IP Address of Client's Machine
    String externalIP = null;
    try
    {
        externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
        externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
    }
    catch (Exception ex)
    {
        logManager log = new logManager();
        log.addLog("Retrieval of IP Address", "IP Address", ex);
    }

    if (!Page.IsPostBack)
    {
        if (!String.IsNullOrEmpty(Session["LoginUserName"].ToString()))
        {
            String loginUsername = Session["LoginUserName"].ToString();

            //Get latest Login time
            DataSet ds = new DataSet();

            ds = al.getAuditData(Session["LoginUserName"].ToString());

            foreach (DataRow r in ds.Tables[0].Rows)
            {
                dateTimeOfLatestLogin = Convert.ToDateTime(r["LastLoginTime"]);
            }

            result = al.trackLogout(loginUsername, DateTime.Now, externalIP, Convert.ToDouble(latitudeTB.Value), Convert.ToDouble(longitudeTB.Value));
            resultLogout = al.updateLLogoutT(loginUsername, DateTime.Now, externalIP);
        }

        loginDetails.InnerText = "You logged into your account at " + dateTimeOfLatestLogin.ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
        logoutDetails.InnerText = "You logged out from your session at " + (DateTime.Now).ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
    }
}

我似乎无法找到错误..我猜它是我的 dateTimedateTimeOfLatestLogin 变量..

al.trackLogout方法,

//Track Logout Activity
public int trackLogout(String username, DateTime dateTimeActivity, String ipaddress, Double latitude, Double longitude)
{
    int result = 0;

    StringBuilder sqlCmd = new StringBuilder();
    sqlCmd.AppendLine("INSERT INTO AuditActivity (Username, DateTimeActivity, IPAddressActivity, LatitudeActivity, LongitudeActivity, ActivityType) ");
    sqlCmd.AppendLine("VALUES (@addUsername, @addDT, @addIPAddress, @addLat, @addLng, @addActivity)");

    try
    {
        SqlConnection myConn = new SqlConnection(DBConnectionStr);

        myConn.Open();

        SqlCommand cmd = new SqlCommand(sqlCmd.ToString(), myConn);

        cmd.Parameters.AddWithValue("@addUsername", username);
        cmd.Parameters.AddWithValue("@addDT", dateTimeActivity);
        cmd.Parameters.AddWithValue("@addIPAddress", ipaddress);
        cmd.Parameters.AddWithValue("@addLat", latitude);
        cmd.Parameters.AddWithValue("@addLng", longitude);
        cmd.Parameters.AddWithValue("@addActivity", "Logout");

        result = cmd.ExecuteNonQuery();

        myConn.Close();

        return result;
    }
    catch (SqlException ex)
    {
        logManager log = new logManager();
        log.addLog("AuditNLoggingDAO.trackLogout", sqlCmd.ToString(), ex);
        return 0;
    }
}

2 个答案:

答案 0 :(得分:1)

不是C#但是没有开放的C#项目可以写入,所以它在VB.Net中;次要的语法调整和更改,但其他方面相同:

Public Function trackLogout(username As String, dateTimeActivity As DateTime, ipaddress As String, latitude As Double, longitude As Double) As Integer
    Dim result As Integer = 0

    Try
        Using conn As New SqlConnection(DBConnectionStr)
            Dim sb As New StringBuilder
            sb.AppendLine("INSERT INTO AuditActivity (Username, DateTimeActivity, IPAddressActivity, LatitudeActivity, LongitudeActivity, ActivityType) ")
            sb.AppendLine("VALUES (@addUsername, @addDT, @addIPAddress, @addLat, @addLng, @addActivity)")

            Using cmd As New SqlCommand() With {.CommandText = sb.ToString(), .Connection = conn, .CommandType = CommandType.Text}
                cmd.Parameters.AddWithValue("@addUsername", username)
                cmd.Parameters.AddWithValue("@addDT", dateTimeActivity)
                cmd.Parameters.AddWithValue("@addIPAddress", ipaddress)
                cmd.Parameters.AddWithValue("@addLat", latitude)
                cmd.Parameters.AddWithValue("@addLng", longitude)
                cmd.Parameters.AddWithValue("@addActivity", "Logout")

                result = cmd.ExecuteNonQuery
            End Using
        End Using
    Catch ex As Exception
        result = -1
        ' Whatever your current implementation is.
    End Try

    Return result
End Function

不幸的是,执行内联sql执行需要StringBuilder。你是对的。我使用存储过程来执行结构化SQL语句,因此我不必在应用程序中管理SQL。

答案 1 :(得分:0)

我现在正在修改的代码..

protected void Page_Load(object sender, EventArgs e)
{
    AuditNLoggingDAO al = new AuditNLoggingDAO();

    int result = 0;

    int resultLogout = 0;

    //Get IP Address of Client's Machine
    String externalIP = null;
    try
    {
        externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
        externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
    }
    catch (Exception ex)
    {
        logManager log = new logManager();
        log.addLog("Retrieval of IP Address", "IP Address", ex);
    }

    CultureInfo provider = CultureInfo.InvariantCulture;

    if (!String.IsNullOrEmpty(Session["LoginUserName"].ToString()))
    {
        String loginUsername = Session["LoginUserName"].ToString();

        //Get latest Login time
        DataSet ds = new DataSet();

        ds = al.getAuditData(Session["LoginUserName"].ToString());

        DateTime dateTimeOfLatestLogin = DateTime.MinValue;

        /*foreach (DataRow r in ds.Tables[0].Rows)
        {
            //dateTimeOfLatestLogin = DateTime.ParseExact(r["LastLoginTime"].ToString(), "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
            String dtDBString = r["LastLoginTime"].ToString();
            dateTimeOfLatestLogin = Convert.ToDateTime(dtDBString);

            //Debug.WriteLine(dateTimeOfLatestLogin);
            //"MM-dd-yyyy HH:mm:ss tt"
        }*/

        String DBConnectionStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

        SqlConnection connection = new SqlConnection(DBConnectionStr);
        string sql = "select LastLoginTime FROM AuditTrails WHERE Username=@USERID";
        SqlCommand command = new SqlCommand(sql, connection);
        command.Parameters.AddWithValue("@USERID", loginUsername);
        try
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    string timeTaken = reader["LastLoginTime"].ToString();
                    dateTimeOfLatestLogin = Convert.ToDateTime(timeTaken);
                }
            }
            connection.Close();
        }
        catch (SqlException ex)
        {
            logManager log = new logManager();
            log.addLog("LogoutWithDesc.aspx.cs", "PageLoad", ex);
        }

        resultLogout = al.updateLLogoutT(loginUsername, DateTime.Now, externalIP);
        result = al.trackLogout(loginUsername, externalIP, Convert.ToDouble(latitudeTB.Value), Convert.ToDouble(longitudeTB.Value));

        loginDetails.InnerText = "You logged into your account at " + dateTimeOfLatestLogin.ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
        logoutDetails.InnerText = "You logged out from your session at " + (DateTime.Now).ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
    }     
}