如何在C#中将MS Access日期转换为字符串 [英] How to convert MS Access date to string in C#

查看:63
本文介绍了如何在C#中将MS Access日期转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将Access中的数据收集到我的texbox中,但是日期不会停止出现错误.有没有办法约会呢?在此站点上的任何地方,我都找不到找到将日期转换为字符串以显示在文本框中的工具.任何帮助都将非常有用,或者我必须将数据库日期更改为字符串.

I was able to gather data from Access into my texboxes, but the dates won't stop giving errors. Is there a way to grab dates or is that impossible? No where on this site can I find a souluiton to convert dates to strings to display into a textbox. Any help would be great or I have to change the database dates to strings.

//Dates not displaying, only errors in the while loop
//strBirthday = dr["STU_BIRTHDAY"].ToString();  This won't diplay like the other 2 strings. 

protected void btnQuery_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\collection\\database.accdb");
        string strQueryString = "SELECT STU_NAME, STU_ADDRESS, STU_BIRTHDATE FROM Students WHERE STU_ID = @SID";
        OleDbCommand com = new OleDbCommand(strQueryString, con);
        com.Parameters.AddWithValue("SID", txtStuID.Text.Trim());
        con.Open();
        OleDbDataReader dr = com.ExecuteReader();

        string strName = "";
        string strAddress = "";
        string strBirthday = "";

        while (dr.Read())
        {
            strName = dr["STU_NAME"].ToString();
            strAddress = dr["STU_ADDRESS"].ToString();
            strBirthday = dr["STU_BIRTHDAY"].ToString();   
        }
        txtStuName.Text = strName;
        txtStuAddress.Text = strAddress;
        txtStuBirthDate.Text = strBirthday;
        dr.Close();
        con.Close();
    }

推荐答案

使用DataReader对象的获取"方法:

Use the "Get" methods of the DataReader object:

DateTime dt = dr.GetDateTime("STU_BIRTHDAY");
txtBirthday = dt.ToString(CultureInfo.CurrentCulture, "yyyy-MM-dd");

通常来说,避免使用Object.ToString().

Generally speaking, avoid Object.ToString().

永远不要将日期作为字符串存储在数据库中,请始终使用数据库的内置日期"或日期时间"类型.还将日期时间值存储为UTC,而不是本地.

Never store dates as strings in a database, always use the database's built-in "date" or "datetime" types. Also store date-time values as UTC, never local.

这篇关于如何在C#中将MS Access日期转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆