user3816352
user3816352

Reputation: 187

How to convert dd/mm to Mysql Datetime format in c#

I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.

I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.

Please help me .

Upvotes: 1

Views: 255

Answers (3)

Rohit Vats
Rohit Vats

Reputation: 81233

You can use Parse method of DateTime:

DateTime dateTime = DateTime.Parse("06/03");

UPDATE

For your comment:

Also after parsing into DateTime i am getting date correct but time i dont want to be 12:00:00 AM instead i want it to be 00:00:00.

12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.

Even if you try to parse exact date, it also creates the same format.

DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss", 
                                         CultureInfo.InvariantCulture);

And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.

Upvotes: 2

Noctis
Noctis

Reputation: 11763

You could do something like

var some_date = "06/03";
var year = DateTime.Now.Year;

var option = some_date+"/"+year;

Or use any of the string formats to bend it to your needs

More on date string format can be found on this MSDN page.


Edit:

If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:

DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00

Upvotes: 1

Suji
Suji

Reputation: 1326

Consider the code: C#

    string s = "06/03";
    System.DateTime dateNow = Convert.ToDateTime(s);

will give the output as you required

in VB.Net :

Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)

Upvotes: 1

Related Questions