Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Worked with phpMyAdmin, and wanted to update data from C#.

I had "yyyy-MM-dd" format for column dateBuy in phpMyAdmin.

To display it, I changed the format to "dd/MM/yyyy" in C#.

This is the code: (I don't have problem with this code)

string dateBuy = dr.GetValue(1).ToString();
DateTime time = DateTime.Parse(dateBuy);
dateBuy = time.ToString("dd/MM/yyyy");

To update database, I wanted to change the format back to "yyyy-MM-dd". But, I had an error: "String was not recognized as a valid DateTime".

This is the error parts of my code:

string dateBuy2 = txtDateBuy.Text;
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();

Did I make mistake in the DateTime syntax? Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

[Since it is not good if we continue in the comments (the comments will be long), I will just put up what I think as a solution here]

To format dateBuy to the format that you want, you should also put the string format in the ToString()

That is, instead of

dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();

put

dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString("yyyy-MM-dd");

Otherwise, it is possible for the ToString() to produce something like "2015-10-16 12:00:00 AM" instead of "2015-10-16"

However, since you use ParseExact, the input for the dateBuy2 must also be in the format of "yyyy-MM-dd" which defeats the purpose. You may consider using DateTimePicker such that you can control the input format.

Alternatively, you can use DateTime.Parse or TryParse (as suggested by Martheen) instead, something like this

try {
    DateTime dt = DateTime.Parse(txtDateBuy.Text);
    dateBuy = dt.ToString("yyyy-MM-dd");
} catch (Exception exc) {
    //wrong format, do something to tell the user
}

If input has to be in the TextBox you better put try-catch to prevent your program crash for taking wrong-formatted input if you use Parse.

Where as if you use TryParseyou can put it in if-else block statement instead

DateTime dt;
if (DateTime.TryParse(txtDateBuy.Text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt)) {
    //correct format, do something using dt
} else {
    //incorrect format, warns the user
}

To get CultureInfo enum you need to add reference to System.Globalization

[Edited after suggestion given by Mr. Soner Gonul]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...