Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an SQLite DateTime value from database and assigning it to a C# string variable

I have a database with a datatable which includes a DateTime column among other things. When using SQL server, I could read the DateTime value from the database using the following code:

    SqlCommand getdate = new SqlCommand("SELECT * FROM EMPinfo WHERE id = @employeeId", connect);
                getdate.Parameters.AddWithValue("@employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
                getdate.Connection = connect;
                connect.Open();
                SqlDataReader readList = getdate.ExecuteReader(CommandBehavior.CloseConnection);
                while (readList.Read())
                {
                    lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
                }

After changing the code to run with SQLite:

    SQLiteConnection connect = new SQLiteConnection(@"Data Source=quotevodata.db;");
                SQLiteCommand getlistname = new SQLiteCommand("SELECT * FROM EMPinfo WHERE id = @employeeId", connect);
                getlistname.Parameters.AddWithValue("@employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
                getlistname.Connection = connect;
                connect.Open();
                SQLiteDataReader readList = getlistname.ExecuteReader(CommandBehavior.CloseConnection);
                while (readList.Read())
                {
                     lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");

                }

I keep getting the following error: "String was not recognized as a valid datetime."

I've tried different combinations and declaration of variables but it's not working out. What is the correct configuration to read DateTime values out of an SQLite database?

like image 737
palm-alchemist Avatar asked Dec 23 '22 20:12

palm-alchemist


2 Answers

SQLite does not have a built-in DateTime object, but rather stores them as Text, Real, or Int values.

From your error, you can infer that it's outputting as text; Which according to SQLite documentation should be in the format of "YYYY-MM-DD HH:MM:SS.SSS"

There are various ways you could parse this to a DateTime object, but I'll use RegEx:

public static DateTime ConvertToDateTime(string str)
{
    string pattern = @"(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})";
    if (Regex.IsMatch(str, pattern))
    {
        Match match = Regex.Match(str, pattern);
        int year = Convert.ToInt32(match.Groups[1].Value);
        int month = Convert.ToInt32(match.Groups[2].Value);
        int day = Convert.ToInt32(match.Groups[3].Value);
        int hour = Convert.ToInt32(match.Groups[4].Value);
        int minute = Convert.ToInt32(match.Groups[5].Value);
        int second = Convert.ToInt32(match.Groups[6].Value);
        int millisecond = Convert.ToInt32(match.Groups[7].Value);
        return new DateTime(year, month, day, hour, minute, second, millisecond);
    }
    else
    {
        throw new Exception("Unable to parse.");
    }
}

docs: http://www.sqlite.org/datatype3.html

like image 86
JonBee Avatar answered Dec 28 '22 05:12

JonBee


Thanks for the answers, I finally got it to work by changing the INSERT statement to SQLite format as suggested:

    string empDob = dateDOB.Value.ToString("yyyy-MM-dd");
    //I then inserted this string into the database with the column configured as a "DATE" datatype.

After that, I used the following statements to read and format the date to usable string and it worked beautifully:

    DateTime dateOfBirthEmp = DateTime.Parse(readList["dob"].ToString());

    lblEmpDob.Text = dateOfBirthEmp.ToString("d");

I really appreciate the help.

like image 44
palm-alchemist Avatar answered Dec 28 '22 05:12

palm-alchemist