2

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

2
  • 1
    Welcome 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 you Commented 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 # Commented Sep 18, 2015 at 7:01

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

you can specify your required format and convert to datetime like this

DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Comments

0

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

I get this error: String was not recognized as a valid DateTime.
@AHIR when do you get this exception? after the conversation of when you insert it into your db?
This error is received before the insert to the database
@AHIR what's the exact type of the column in your db?(e.g int , text etc)
DateTime.Parse uses current culture, if in current culture dates are not represented as the input string it will throw exception
|
0

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))
    {
        ...
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.