objTour.tourStartDate =
Convert.ToDateTime(
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", null)
.ToString("MM/dd/yyyy"));
where txtTourStartDate.Text="16/08/2012"
.
I have searched and read all posts related to this.
In a custom date format string, /
denotes the culture-specific date separator, not the literal character /
. Thus, the result of your code depends on the user's (or the server's) localization settings.
To make your code independent of culture-specific settings, you have two options:
Explicitly specify a culture that uses a slash as the date separator, e.g.
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture)
or escape the character, e.g.
DateTime.ParseExact(txtTourStartDate.Text, @"dd\/MM\/yyyy", null)
(note the @
and the \
).
Both should yield the desired result.
This will be enough:
objTour.tourStartDate = DateTime.ParseExact(txtTourStartDate.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
Your original code works, although you are doing lot of unnecessary conversions. (DateTime -> ToString -> ToDateTime), the real issue is InvariantCulture
. Since you are passing null
for CultureInfo
try CultureInfo.InvariantCulture
.
Your original code:
objTour.tourStartDate =
Convert.ToDateTime(
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy"));
A better one could be:
objTour.tourStartDate =
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)