如何使用sqlite读取年月日期格式,c#

时间:2013-12-04 22:59:53

标签: c# sqlite

我的问题:

我在表格中有数据,格式为YYYY-MM ex:2001-02。 当我从我的数据库中查询,并将这些值存储在要显示到列表视图的列表中时,输出变为1/1/2001 12:00 am(不希望它采用此日期时间格式)。

   string sql6 = "select YYMM, TotalTrans  from t2 where cast(TotalTrans as int) < 1000";
   SQLiteCommand command3 = new SQLiteCommand(sql6, sqlite_conn);


   SQLiteDataReader reader3 = command3.ExecuteReader();

   while (reader3.Read())
   {


       DateTime yyyymm;  

       if (DateTime.TryParse(reader3["YYMM"].ToString(), out yyyymm))
       {
           YYMM.Add(yyyymm);

       }
   }

基于SO用户帮助,我尝试运行修改查询并使用strftime。

但是现在我的列表中没有任何值(YYMMt21 - 我用来填充列表视图)

        string sql13 = "SELECT YYMM FROM t2 WHERE strftime('%Y-%m', YYMM) = '2002-02'";

        SQLiteCommand cmd4 = new SQLiteCommand(sql13, sqlite_conn);

        SQLiteDataReader rdr4 = cmd4.ExecuteReader();

        while (rdr4.Read())
        {

           // int TotalTranst21;


          int yyyyyy;
            if (int.TryParse(rdr4["YYMM"].ToString(), out  yyyyyy) )
            {
                YYMMt21.Add(yyyyyy);

            }
        }

4 个答案:

答案 0 :(得分:1)

您应该让程序逻辑为您执行日期格式化。在您的代码中,您的DateTime对象就像您看到它一样格式化字符串 - 无论日期字符串在SQL中的外观如何,它都将成为DateTime对象[因此DateTime.TryParse()]。

查看有关日期格式的MS文档。

http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx

作为旁注,与其他SQL数据库系统不同,SQLite中没有DateTime的字段类型。您可以将它们存储为整数或文本,并使用链接中引用的内置函数,如下所示。

http://www.sqlite.org/lang_datefunc.html

答案 1 :(得分:1)

您应该使用完整格式的商店日期:YYYY-MM-DD HH:MM:SS.SSS 如果您只需要存储时间或仅存储日期

,则无关紧要

您也可以使用其他格式的日期和时间:

<强> REAL

朱利安日数字,即公元前4714年11月24日格林威治中午以来的天数。根据公历格里高利历。

<强> INTEGER as Unix Time,自1970-01-01 00:00:00 UTC以来的秒数。

只有在那之后,strftime才能正常工作。

答案 2 :(得分:1)

试试这个

string Mydate = Convert.ToDateTime(rd4["YYMM"]).ToString("yyyy");

您将获得年度

如果你使用它:

string Mydate = Convert.ToDateTime(rd4["YYMM"]).ToString("d");

您将获得结果dd-mm-yyyy(或作为区域设置)

答案 3 :(得分:1)

首先,您希望在列表中显示什么? YYYY-MM,就像数据库一样?如果是这样,请不要将int解析为DateTime,只使用返回的字符串。

现在,代码......

SQL:

 string sql6 = "select YYMM, TotalTrans  from t2 where cast(TotalTrans as int) < 1000";
 //If you are just using YYMM, why choosing two columns???

 string sql13 = "SELECT YYMM FROM t2 WHERE strftime('%Y-%m', YYMM) = '2002-02'";
 //If dates in database are already in YYYY-MM format, why use STRFTIME?
 //STRFTIME will fail (return NULL), as YYYY-MM is not a valid SQLite date string

解析:

   //if (DateTime.TryParse(reader3["YYMM"].ToString(), out yyyymm))
   //if (int.TryParse(rdr4["YYMM"].ToString(), out  yyyyyy) )
   //No sense at all. Just use supplied string:
   YYMMt21.Add(rdr4["YYMM"].ToString());

结论:

SQLiteCommand command3 = new SQLiteCommand("SELECT YYMM FROM t2 WHERE TotalTrans<1000", sqlite_conn);
SQLiteDataReader reader3 = command3.ExecuteReader();
while (reader3.Read()) {
    YYMM.Add(reader3["YYMM"].ToString());
}

......够了!

相关问题