Reputation: 65
I have tried with
protected void gridCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime olddate = Convert.ToDateTime(e.Row.Cells[9].Text);
// Error : String was not recognized as a valid DateTime./ 'DateTime today = DateTime.Now;'
if (olddate > today)
{
Label status = (Label) e.Row.FindControl("lblStatus");
status.Text = "AutoHold";
}
}
}
Upvotes: 3
Views: 498
Reputation: 98750
Convert.ToDateTime
method uses your CurrentCulture
settings by default if you don't provide any IFormatProvider
as a second parameter.
That means, your CurrentCulture
doesn't have yyyy-MM-dd
as a standard date and time format.
In such a case, you can specify your string format with DateTime.TryParseExact
or DateTime.ParseExact
methods like;
DateTime olddate;
if(DateTime.TryParseExact(e.Row.Cells[9].Text, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out olddate))
{
// Your olddate will be 28/03/2015 00:00:00
}
but in old date getting '1/1/0001' where as in my grid cell i have '4/1/2015' by above your mentioned code.
Clearly, your 4/1/2015
doesn't match with yyyy-MM-dd
format, that why your olddate
will be the default value of DateTime
which is DateTime.MinValue
(1/1/0001)
.
If your string can be more than one format, DateTime.TryParseExact
has an overload that takes formats as a string array. With that, you can specify all possible formats your string.
For example;
string s = "4/1/2015";
DateTime dt;
var formats = new string[]{"yyyy-MM-dd", "M/d/yyyy"};
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// Your dt will be 01/04/2015 00:00:00
}
Upvotes: 1
Reputation: 1185
Use DateTime.ParseExact
string res = "2012-07-08";
DateTime d = DateTime.ParseExact(res, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy")); // can set any format
Upvotes: 0
Reputation: 1443
Replace this line in code
DateTime olddate = DateTime.ParseExact(e.Row.Cells[9].Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Convert.ToDateTime
will throw exception if there is a difference in current culture and the format of date time string
Upvotes: 0
Reputation: 638
use:
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "2015-03-28";
format = "yyyy-MM-dd";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
Upvotes: 0