ASP.NET MVC 3 Razor DateTime.Parse don't work - asp.net-mvc-3

I'm trying to do a cast with dates but it's throws me an exception
.
The code is:
This Works ->
var FechaInicio = Model != null ? DateTime.Parse(Model.FechaInicio).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
This Doesn't Work ->
var FechaFin = Model != null ? DateTime.Parse(Model.FechaFin).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
The model is Ok and values are dates in string format
The error is:
Server Error in '/' Application.
String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
Source Error:
Line 13: var Ubicacion = Model != null ? Model.Ubicacion : null;
Line 14: var FechaInicio = Model != null ? DateTime.Parse(Model.FechaInicio).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
Line 15: var FechaFin = Model != null ? DateTime.Parse(Model.FechaFin).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");

The error is straight-forward. The string being passed to Parse could not be interpreted as a valid DateTime. By default, the format of the current culture is employed, when using Parse. Not sure what that is exactly in your case, but it would likely be the same as you would see by outputting DateTime.Now.ToString().
The reason DateTime.Today.ToString() failed, is because the output will only have a date component. The default format utilized by Parse will require date and time components.
If you need to parse a string into a DateTime that doesn't match the format of the current culture, then you need to use ParseExact instead of Parse and pass a format string that shows how the string-based datetime is formatted.

Related

Laravel Datepicker Failed to parse time string

I'm trying to build a query in Laravel using whereBetween and I have a problem with the dates-range. I'm using Carbon to get the inputs, looking like this:
$dateRange = Carbon::parse($request->get('anniversary'));
I received the following error on submit:
DateTime::__construct(): Failed to parse time string (06/01/2019 - 06/30/2019) at position 11 (-): Unexpected character
Then, I changed the $dateRange in this form:
$dateRange = Carbon::parse(str_replace('-', '', $request->get('anniversary')));
After that, this error occured:
DateTime::__construct(): Failed to parse time string (06/01/2019 06/30/2019) at position 12 (0): Double date specification
The whereBetween clause looks like this:
->whereBetween('anniversary', [$dateRange])
Any ideas on how can I fix this?
You need to explode the retrieved Datepicker to two values. (Start Date and End Date)
$dateArray = explode('-', $request->get('anniversary'));
$startDate = $dateArray[0];
$endDate = $dateArray[1];
Now you can use
->whereBetween('anniversary', $dateArray);

Linq where condition on datetime.ToString()

I have following Linq code
// query = IQueryable<DataClass>
query = query.Where(m => m.Column1.Contains(model.search.value)
|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value));
return query.ToList() // here the error is thrown
I get NullReferenceException error
Exception has occurred: CLR/System.NullReferenceException An exception
of type 'System.NullReferenceException' occurred in
Microsoft.EntityFrameworkCore.dll but was not handled in user code:
'Object reference not set to an instance of an object.' at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
if i commented out the line for 2nd column it works
//|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value)
model.search.value is string value I am trying to filter all columns. The DateTimeColumn2 is in DateTime datatype in the database, but user input string, therefore Iam converting DateTimeColumn2 to string and try to filter to users value. Any idea, what I am doing wrong ?
What happens here is that the part...
|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value)
...can't be translated into SQL (ToString("dd.MM.yyyy") isn't supported`), so EF-core auto-switches to client-side evaluation.
However, now the whole Where clause is evaluated client-side, including the first part,
m.Column1.Contains(model.search.value)
Now this first part has become susceptible to null reference exceptions. There are entities that have a null for Column1.
When you remove the DateTimeColumn2 predicate the whole statement can be translated into SQL and evaluated by the database.
It is likely that your DateTimeColumn2 can have NULL values which is very normal for DateTime columns. Also you shouldn't convert it to a string but the search value to a datetime. Is the user searching like "01" to mean any 1st date of any month and\year?
query = query.Where(m => m.Column1.Contains(model.search.value)
|| !m.DateTimeColumn2.HasValue
|| m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value));
return query.ToList()
If you think that the exception is thrown because of any of the DateTimeColumn2 values might be null, check for non-nullness:
query = query.Where(m => ...
|| (m.DateTimeColumn2 != null &&
m.DateTimeColumn2.ToString("dd.MM.yyyy").StartsWith(model.search.value)));

Birt Report parameter validation

NewParameter is of type DATE and having Custom Format as MM/dd/yyyy in parameter window.
I have written the following code to verify whether the user is sending correct format or not. If user sends 24/12/2014 the code should throw error as Invalid format. But the following code is throwing the error even while user send the correct format e.g: 11/10/2014
importPackage(Packages.java.lang);
importPackage(Packages.java.text);
sdf = new SimpleDateFormat("MM/dd/yyyy");
testDate = null;
dateerror=false;
try {
testDate = sdf.parse(params["NewParameter"]);
dataerror=false;
} catch (e) {
errorMessage = "the date you provided is in an invalid date";
eee = e;
dateerror=true;
reportContext.getDesignHandle().findElement("mytable").drop();
}
It seems there is a confusion: when we declare a report parameter as "DATE", we don't have to parse it in report scripts because it is already a java Date object. Therefore this line of code is wrong, because the parser would expect a "String" type:
testDate = sdf.parse(params["NewParameter"]);
The custom format "MM/dd/yyyy" you linked to the report parameter is not actually used by the report engine: it is only taken into consideration by the webviewer, to specify how dates should be displayed in parameters dialog.
The best way to achieve your requirements would be to customize client-side javascript of your webviewer, in order to control date format in web-browsers. An example of this approach allows to enter dates through a calendar such here.
Otherwise if you really need to validate a format during report execution, although it is not very elegant the only way would be to set your parameter as "String" type and put your script in "Initialize" event of the report. However in this case you would have to parse it each time it is used in a dataset, or parse it once in a report variable.

Linq-to-SQL DataContext update

I am getting this runtime exception
Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to
type 'System.String'.
How can I fix my code to get my result without exceptions?
ProductsDataContext db = new ProductsDataContext();
var matchedproduct = db.GetTable<product>().SingleOrDefault(p =>p.ProductID==productID);
if (matchedproduct != null)
product.ProductName = txtpname.Text;
db.SubmitChanges();
If you aren't getting a compile time error its because your dbml doesn't accurately depict the column in your database. Your object thinks its a string but its clearly a decimal in the database. You should update it in the dbml editor. Then when you set product name you will have to parse out the decimal value from the Text.

MVC Razor Web Grid- Error

I am using MVC3 webgrid. I am displaying the data in a webgrid and before displaying the data I have to calculate the number of days between start date and end date. I am using the following code.
int noOfAbsenceDays = item.AbsEnd?(item.AbsEnd.Subtract(item.AbsStart)).Days: (item.DateTime.Now.Subtract(item.AbsStart)).Days;
It complains about this error
Cannot implicitly convert type 'System.DateTime' to 'bool'
I don't know where it is coming from?
Thanks
You can try the following code:
int noOfAbsenceDays = item.AbsEnd == null ? (item.AbsEnd.Subtract(item.AbsStart)).Days : (item.DateTime.Now.Subtract(item.AbsStart)).Days;

Resources