'Getting a datetime variable from a database using dataTableReader
So i have a database and i am getting from it it's data by dataTableReader.
I think when you get them from the database you get them as an object, not sure, but for sure it's not the variable i set them to be in the database.
so fur I have used only int and varchar in the database so i have converted them by using toString() and int.parse(). now i need to use a datetime variable.
How can i get it from the database as a datetime or convert it to datetime and not as string(using toString())? Thanks for the Help
Solution 1:[1]
This should do in most cases:
var datetime = DateTime.Parse("string");
The string being the string saved in the database
Solution 2:[2]
How can i get it from the database as a datetime or convert it to datetime and not as string(using toString())?
Solution 1: if you are storing the Date value as DateTime type then you can directly convert into DateTime using Convert.ToDateTime() method
Try This:
DataReader dr = new DataReader();
DateTime dt;
while(dr.Read())
{
dt = Convert.ToDateTime(dr["DateColumn"]);
}
Solution 2: If you are storing the Date in some fixed format like dd-MM-yyyy as VARCHAR then you can use DateTime.ParseExact() method
Try This:
DataReader dr = new DataReader();
DateTime dt;
while(dr.Read())
{
dt = DateTime.ParseExact(dr["DateColumn"].ToString(),"dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
}
Solution 3:[3]
Try Convert.ToDateTime(myDataReader[i]) where i is the index of your column.
Solution 4:[4]
try this dateTimePicker_dob.Value = Convert.ToDateTime(dr[i].ToString());
in here i is the index of your DB column and dateTimePicker_dob is your dateTimePicker Design(Name)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amit Joki |
| Solution 2 | Sudhakar Tillapudi |
| Solution 3 | rory.ap |
| Solution 4 | Dhamith Kumara |
