I'm using C# and Mysql database.
How to convert string to timestamp for insert into mysql? For example, I have string:
28.9.2015 05:50:00
-
1Welcome to stack, tje rule is simple, you try something but got stuck or false result then you show us what u did and then we try to help point out your mistake and not solve the entire problem for youKumar Saurabh– Kumar Saurabh2015-09-18 06:57:01 +00:00Commented Sep 18, 2015 at 6:57
-
@KumarSaurabh I am a PHP programmer and the programming language C # I am new. PHP String conversion to Time Stamp in there. But I want to know how to do this in C #user2598812– user25988122015-09-18 07:01:30 +00:00Commented Sep 18, 2015 at 7:01
Add a comment
|
4 Answers
DateTime.ParseExact is what you need:
DateTime date = DateTime.ParseExact("28.9.2015 05:50:00", "dd.M.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Comments
I couldn't find what so difficult here... simply use the DateTime.Parse method
DateTime date = DateTime.Parse("28.9.2015 05:50:00");
Not sure if it would work but try this
DateTime date = DateTime.ParseExact("28.9.2015 05:50:00", "dd.M.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Now you can insert it into your database as a date type.
Goodluck.
6 Comments
Slashy
@AHIR when do you get this exception? after the conversation of when you insert it into your db?
Slashy
@AHIR what's the exact type of the column in your db?(e.g int , text etc)
Matteo Umili
DateTime.Parse uses current culture, if in current culture dates are not represented as the input string it will throw exception
|
Use DateTime.ParseExact:
using using System.Globalization;
string date = "31/12/2018";
dateParsed = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
In query database:
using (MyAppContext c = new MyAppContext())
{
foreach (DbValues dbValues in c.DbValues.Where(a=> a.Timestamp < dateParsed))
{
...
}
}