简体   繁体   中英

Parse a string to datetime format

I have here a little problem and would like to know where is my mistake and how to correct it.

string preConvDATE = monthCombobox2.Text + " " + datecombobox2.Text + ","+ "0000";
//lets say the comboboxes contain something like this "January 1";

DateTime DT = DateTime.ParseExact(preConvDATE, "MMMM d, yyyy 00:00:00", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-mm-dd");
    try
    {
       //code that inserts strDate to a column in Mysql DB
    }
    catch
    {
      //msg
    }

why "0000" for the year? because i was really planning to store just the month and date, but realized i could just store it as a datetime format with a year, and then at viewing the table i'd just use the Mysql MONTH() and DATE() function concatenated to view the Month and Date i stored from the monthCombobox2 and datecombobox2 .

I also tried:

Convert.ToDateTime()

But still won't work.

How do i properly parse MMMM d,yyyy date format so that i could convert it to yyyy-mm-dd again and store it as datetime format in the database? Thank you so much :)

As I can see, you are using text boxes to catch the value of month and date, instead of that you can use dropdowns which will display the month name but return the values like 01 for January and so on. It will be easy for you to format date formats. You don't want to save year that's okay, instead of setting 0000 you can set the current year. Now the problem with that you will not able to figure out the what exactly day was it (eg Sunday, Monday and so on).

string preConvDATE = monthCombobox2.Text + "/" + datecombobox2.Text+"/" + DateTime.Now.Year.ToString();
DateTime DT = DateTime.ParseExact(preConvDATE, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

string strDate = DT.ToString("yyyy-MM-dd");

I hope this will solve your problem. Happy Coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM