Reputation: 2841
I have dates in SQL stored as DateTime, when showing them in a textbox I do this:
txtDateLogged.Text = v.DateLogged.ToString("dd-MM-yyyy");
But when I the update that textbox to write back to SQL Im getting and invalid DateTime error when using this:
if (DateLogged!= "")
{
uInput.DateLogged = Convert.ToDateTime(DateLogged);
}
Im assuming Im missing something in the formatting - the date value is passed into the public void doing the update as a string, then converted in the line above. Any suggestions?
thanks
T
Upvotes: 1
Views: 2201
Reputation:
In SQL convert Date filed in 105 Format
e.g.
select Convert(varchar(20),getdate(),105)
Upvotes: 0
Reputation: 6260
You can also use DateTime.TryParse
and parse string value using CultureInfo
.
User will be able to input data using culture specific formatting and that you can just convert it to InvariantCulture
:
DateTime b;
bool isCorrectValue = false;
CultureInfo uiCulture = Thread.CurrentThread.CurrentUICulture;
if (DateTime.TryParse(DateLogged, uiCulture, DateTimeStyles.None, out b))
isCorrectValue = true;
Upvotes: 0
Reputation: 15144
Maybe use:
uInput.DateLogged = (new DateTime(year, month, day))
And extract the year/month/day parts from DateLogged.
EDIT:
Since you know the date in your string is "dd-MM-yyyy", then this is how you extract the parts:
int year = Convert.ToInt16(DateLogged.Substring(6, 4));
int month = Convert.ToInt16(DateLogged.Substring(3, 2));
int day = Convert.ToInt16(DateLogged.Substring(0, 2));
If by MM you mean "JA" - then you need to convert "JA" to "01" or 1.
Upvotes: 0
Reputation: 1499800
You need to convert back in the same format that you converted to text, e.g.
uInput = DateTime.ParseExact(text, "dd-MM-yyyy", CultureInfo.InvariantCulture);
See the docs for DateTime.ParseExact
for more details.
Of course, if you could avoid converting to a string representation - or keep the DateTime
as well - that would be better.
If you're parsing user input you should use DateTime.TryParseExact
instead, to account for the possibility of invalid data without using exceptions for flow control.
Upvotes: 8