Reputation: 21
I get an exception with the error message -
"System.FormatException: String was not recognized as a valid DateTime."
on the following line:
DateTime RecDate = RecDateSearch == string.Empty ? Convert.ToDateTime("1/1/1970").Date : Convert.ToDateTime(RecDateSearch).Date;
When choose day in the date less than 12 like 10/1/2021 or 12/12/2020, I get no exception. But when choose day in the date more than 12 like 20/1/2020 or 23/12/2020, I get this exception.
This is my javascript code -
var myTable = $('#m_table_1').DataTable({
"processing": true,
"serverSide": true,
"dom": '<"top"i>rt<"bottom"lp><"clear">',
"scrollY": 200,
"scrollX": true,
"ajax": {
"url": '@Url.Action("AllPOSDonations", "POSDonation")',
"type": "POST"
},
columns: [
{ data: "Id" },
{ data: "No" },
{
data: "DonationDate", render: function (d) {
return moment(d).format('YYYY/MM/DD');
}
This is my razor code -
<div class="form-group" id="datepickerDiv">
<input type="text" id="recDate" class="form-control" data-date-container='#datepickerDiv' />
</div>
Upvotes: 0
Views: 948
Reputation: 55806
As you supply a well-formatted string for a date value, use the more forgiving Parse
method, and you can reduce to:
DateTime RecDate = RecDateSearch == string.Empty ? new DateTime(1970, 1, 1) : DateTime.Parse(RecDateSearch);
Console.WriteLine(RecDate.ToString("yyyy/MM/dd"));
Results:
string RecDateSearch = string.Empty;
// RecDate -> 1970-01-01
string RecDateSearch = "2020/01/20";
// RecDate -> 2020-01-20
Upvotes: 0
Reputation: 3946
Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown
Use DateTime.ParseExact
DateTime date = DateTime.ParseExact(RecDateSearch, "dd/MM/yyyy", null);
Upvotes: 1