Date in model is null unless in US format - c#

I am using daterangepicker. In my form, I have two hidden fields:
#Html.HiddenFor(x=> x.Header.StartDate, new {id="startdate"})
#Html.HiddenFor(x => x.Header.EndDate, new { id = "enddate" })
I also have the input which is for the dates to be selected from:
<input class="input-sm form-control" placeholder="Enter your dates" type="text" name="daterange" value="" />
When the user has selected an end date, the two hidden fields are populated with the start and end date, respectively.
The daterangepicker is managed via JS:
$(function () {
$('input[name="daterange"]').daterangepicker({
locale: {
format: 'DD/MM/YYYY'
},
"autoApply": true
});
$('input[name="daterange"]').val('');
$('input[name="daterange"]').on('apply.daterangepicker', function (ev, picker) {
var startdate = picker.startDate.format('DD/MM/YYYY');
var enddate = picker.endDate.format('DD/MM/YYYY');
$("#startdate").val(startdate);
$("#enddate").val(enddate);
});
});
My HeaderViewModel looks like this (setting the format makes no difference):
public class HeaderViewModel
{
//[DataType(DataType.Date), DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
// [DataType(DataType.Date), DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
}
If I choose a date with a day less than 12, eg: 11 March 2015, it works. However, if I select a date, say, 23 March 2015, it will not work because the date is invalid... it is expecting a US format.
I am using SQL server 2012 and have set the language to British English.
Anyone have any ideas? It's killing me.

Related

Formatting DateTime string inside of a linq statement

I have a web api set up where I'm displaying information on my site via entity framework. I'm filtering my data so it only pulls back the specific parts I want, which includes a DateTime value.
[HttpGet]
public IEnumerable<Log> XmlLog()
{
var userLog = _db.Logs.Where(x => x.EngineType == "Xml");
return userLog .ToList();
}
This displays my date as:
2019-02-05T15:11:50.39
What I need to do is change the DateTime format to be something else. Ideally:
Saturday 2 February 9:12:30
On my linq call I've tried the following:
[HttpGet]
public IEnumerable<Log> XmlLog()
{
var userLog = _db.Logs.Select(d => d.LogDate.ToString("f")).Where(x => x.EngineType == "Xml");
return userLog .ToList();
}
And on my model itself I have tried the following attributes:
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm:ss}")]
public DateTime LogDate { get; set; }
Neither of my attempts has worked. What is it I'm doing wrong in my statements?
The above is written in DotNet 4.7 and not in DotNetCore.
As John has commented, your LINQ should be throwing an exception, because you first select strings, and then try to filter them as though they are objects.
But this approach is backwards anyway. This is just about getting the data, so it should just stay as it is, without any formatting. Let your view layer be responsible for formatting.
The DisplayFormat attribute is great, but only if you are using Html.DisplayFor/Html.EditorFor helpers. If you are doing just something like #Model.LogDate in your view, consider calling ToString(format) with the format you need.
Finally, your format does not look like example you wish it was. The correct format you are looking for is: dddd, dd MMMM HH:mm:ss.
All in all, leave the filter as it is, and either use DisplayFor with this annotation:
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dddd, dd MMMM HH:mm:ss}")]
public DateTime LogDate { get; set; }
...
#Html.DisplayFor(m => m[i].LogDate)
Or don't bother with any annotations, and just use
#Model[i].LogDate.ToString("dddd, dd MMMM HH:mm:ss")

MVC 4 models not accept jquery datapicker date format

I am using Entity framwork 6 , MVC 4 and jquery datepicker. When fill all the form data and press the submit button the ModelState.IsValid always return false value, because the jquery datepicker value not match with the model validation field.
in .cshtml file
-----
-----
#Html.TextBoxFor(m => m.Annieversary, new { id = "anudate", #class = "form-control datetimepicker", #placeholder = "Annieversary Date" })
-----
-----
c# Side
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date, ErrorMessage = "Date required")]
public Nullable<System.DateTime> Annieversary { get; set; }
I tried below
#Html.TextBoxFor(m => m.Annieversary,"{0:dd/MM/yyyy}", new { id = "anudate", #class = "form-control datetimepicker", #placeholder = "Annieversary" })
This is also not match with the model, always return null value. I know c# only accept the "MM/DD/YYYY" format but jquery datepicker return "DD/MM/YYYY" format. How can I solve this problem?
First of all, let's simplify so it can work. Then you can add the attributes you feel you need.
Model
Notice that I am using the question mark to make the field nullable - as I understand you will need it:
public DateTime? Anniversary { get; set; }
View
Notice the datepicker class, which we will use to call the jQuery UI DatePicker component:
#Html.TextBoxFor(m => m.Anniversary, new { #class = "datepicker" })
JavaScript
Notice that I am setting the dateFormat to the format you need. That helps but it's not enough just yet:
<script>
$(function () {
$(".datepicker").datepicker({ dateFormat: "dd/mm/yy" });
});
</script>
Web.Config
Now, here is where the magic happens. You need to set the culture of your application in order to have the proper date format. I have it set to pt-BR, which gives the same date format you need:
<globalization culture="pt-BR" uiCulture="pt-BR"/>
That should do it, but it's the most basic example.
The most important thing to remember is: The date format should always match the culture you set in the web.config.

how to convert 2005-05-05 22:12 PM in to just dd/mm/yy

how to convert 2005-05-05 22:12 PM in to just dd/mm/yy
and why i am getting in the form of "/Date(1487548800000)/" while i am binding in view using angular js
public JsonResult GetAll()
{
Entities contextObj = new Entities();
var employeeList = contextObj.CCFFares.ToList();
//return Json(employeeList, JsonRequestBehavior.AllowGet);
DateTime date = DateTime.Now;
return this.Json((from obj in contextObj.CCFFares
select new`enter code here`
{
ID = obj.ID,
Departure_Airport = obj.Departure_Airport,
Destination = obj.Destination,
Departure_Date = obj.Departure_Date,
Return_Date = obj.Return_Date,
Airline = obj.Airline,
Fare = obj.Fare,
Offer_Ends = obj.Offer_Ends,
Ailine_Class = obj.Airline_Class
}), JsonRequestBehavior.AllowGet);
}
GetData.then(function (fair) {
$scope.fairs_destination = fairs.Destination;
$scope.fairs_departure_date = $filter('date')(fairs.Departure_Date, 'dd/mm/yyyy');
$scope.fairs_return_date = fairs.Return_Date;
}
I have wrote the C# code and the angular js function in the second method and finally i have represent the html angular js bind. can anyone please guide me on how to fix the date into plain dd/mm/yy format. and the date format is in DateTime format in sql getter setter access specifiers
<tr ng-repeat="fairs in fairs_deals | filter:query | orderBy:'ID'">
<td>{{fairs.ID}}</td>
<td>{{fairs.Departure_Airport}} </td>
<td>{{fairs.Destination}}</td>
<td>{{fairs.Departure_Date}}</td>
<td>{{fairs.Return_Date}}</td>
<td>{{fairs.Airline}}</td>
<td>£{{fairs.Fare}}</td>
<td>{{fairs.Offer_Ends}}</td>
<td>{{fairs.Ailine_Class}}</td>
<td>
Inject $filter in your controller and use this code to convert into any format:
$scope.formatted_datetime = $filter('date')($scope.variable_Containing_time,'dd/mm/yyyy');

Setting a DateTime appointment schedule

Newbie question about using the DateTime method to set a schedule inside a Telerik calendar. I want to use the Telerik controls calendar to set a schedule for a music bands tour schedule.
I can't seem to get the desired results. Below is the code in my SampleAppointmentSource CS file. I thought that by setting the DateTime.Parse("5/19/2013") that then in all of the appointments when I use the AddDays(1) or AddDays(20) the appointemnts would follow the DateTime.Parse("5/19/2013") pattern but it doesn't. The appointments always use the current date and time (Now). When I add the days, the appointments aren't added to the Parsed date ("5/19/2013"), they are added to the current DateTime. Like the appointments are always referenced to the current system date.
I hope that wasn't to confusing....
What do I need to use to get the desired results?
Is it because of the DateTime.Now.AddDays(1) line? Should it not be DateTime.Now?
{
public class SampleAppointmentSource : AppointmentSource
{
public SampleAppointmentSource()
{
DateTime date = new DateTime();
date = DateTime.Parse("5/19/2013");
}
public override void FetchData(DateTime startDate, DateTime endDate)
{
this.AllAppointments.Clear();
this.AllAppointments.Add(new SampleAppointment()
{
StartDate = DateTime.Now.AddDays(1),
EndDate = DateTime.Now.AddDays(1),
Subject = "Jackson W/Warren Hayes",
AdditionalInfo = "Fain Feild",
Location = "LoserVille,Kentucky",
});
Fleshing out my comment to your question. You create a DateTime object called date and never use it. DateTime.Now will always return an object containing the current DateTime. You need give your date DateTime object module Level scope so you can access it in your FetchData method. See if something like this works for your.
public class SampleAppointmentSource : AppointmentSource
{
DateTime date;
public SampleAppointmentSource()
{
date = DateTime.Parse("5/19/2013");
}
public override void FetchData(DateTime startDate, DateTime endDate)
{
this.AllAppointments.Clear();
this.AllAppointments.Add(new SampleAppointment()
{
StartDate = date.AddDays(1),
EndDate = date.AddDays(1),
Subject = "Jackson W/Warren Hayes",
AdditionalInfo = "Fain Feild",
Location = "LoserVille,Kentucky",
});
}
}

Create an Editor Template for DateTime with three input fields for day, month, year, in MVC

I would like to create an editor template for DateTime? field that has 3 text boxes for day, month, year. Currently my EditorTemplates/Date.cshtml looks like this:
#Html.TextBox(string.Empty, Model.HasValue ? Model.Value.Day.ToString() : "",
new { #class = "day-box", title = "day", min = "1", max = "31", type = "number" })
#Html.TextBox(string.Empty, Model.HasValue ? Model.Value.Month.ToString() : "",
new { #class = "month-box", title = "month", min = "1", max = "12", type = "number" })
#Html.TextBox(string.Empty, Model.HasValue ? Model.Value.Year.ToString() : "",
new { #class = "year-box", title = "year", min = "1900", max = "2020", type = "number" })
The obvious problem is that that (as is) the id and name attributes all get set to the same value. I need to append something to those values, and never make it back into my model.
I was hoping that appending _Day to the id, and .Day to the name of the Day input, and likewise for month and year would solve the problem. But I can't see an easy way of doing this.
I was going to use Hidden input for the actual value, then use javascript to update the value of the hidden field each time a value changes in one of my three (d/m/y) textboxes.
So is there a way to get the name and id that MVC is going to use, when I pass in string.Empty? Using ViewData.TemplateInfo.HtmlPrefix doesn't seem to give full value.
Is there a better way to do what I want? I can't imagine I am the first to tackle this.
I know there are 3rd party date pickers out there. For the sake of this problem I am not interested in them.
Thanks,
~S
Had DateTime's Year Month Day are settable, you can just do this on your DateTime.cshtml EditorTemplates
#model System.DateTime
#Html.TextBoxFor(model => model.Year) / #Html.TextBoxFor(model => model.Month) / #Html.TextBoxFor(model => model.Day)
Above isn't possible. DateTime's Year, Month and Day properties are read-only.
What you can possibly do is to just create a separate data type:
public struct DatePart
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public DateTime Date { get { return new DateTime(Year, Month, Day); } }
}
Then do this on your date EditorTemplates
#model TestV.Models.DatePart
#Html.TextBoxFor(model => model.Year) / #Html.TextBoxFor(model => model.Month) / #Html.TextBoxFor(model => model.Day)
Then just access DatePart's Date(DateTime type) property
You can form date from three field in your custom template with javascript and write it in hidden field that will bind to your Model.Date

Categories