4

How to convert C# Datetime.Today, into Timestamp format 10/20/2011 12:00:00 in mysql?

2
  • Are you asking how to do this in C# or how to do this in Mysql? Commented Oct 20, 2011 at 8:28
  • Have you considered using parameterized queries instead? Commented Oct 20, 2011 at 8:29

5 Answers 5

11

If you want to get the date time as a string in that format then you can do...

string dt = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

See here for extra formatting options for the DateTime ToString method

Though from my understanding of MySQL it will accept a timestamp in the format yyyy-MM-dd HH:mm:ss. I would recommend doing this as it will ensure dates like 05/08/2011 are parsed correctly for the right month and day...

string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Sign up to request clarification or add additional context in comments.

2 Comments

Correct format string to "MM/dd/yyyy HH:mm:ss" (according to OP question) and you get +1 from me :)
it suppose to be pm but store in mysql it is am
2

Try this:

DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

and if you want more/other time formats, check this.

Comments

1

You can use something like following and use return value as timestamp for Sql.

public static string GiveMeTimestamp(DateTime value)
{
 return value.ToString("yyyy/MM/dd HH:mm:ss:ffff");
}

Comments

0

Use the overloaded ToString method which takes a string argument for the format.

Comments

0

This Possibly may assist someone with the same approach and thought that I had:

To test directly in MYSQL Workbench:

INSERT into tblDemo VALUES (898,CURRENT_TIMESTAMP());

create table tblDemo (ScenarioID INT(10),
          ProcessTime  DATETIME DEFAULT CURRENT_TIMESTAMP() NOT NUll);

Now compile the string in your C# Code like so:

    string query = "INSERT into tblDemo " + 
                    "VALUES (" +  ScenarioID + "," +  " CURRENT_TIMESTAMP())";

Note the CURRENT_TIMESTAMP() in quotes in the above query

Output: '2021-03-04 17:52:30'

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.