[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 TryParse
you 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]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…