Convert date from jquery in DateTime - c#

I use the jquery ui controls.
I have a datepicker and I retrieve the date as follows:
var sDate = $("#startDatePicker").datepicker('getDate');
var eDate = $("#endDatePicker").datepicker('getDate');
which as an example for sDate returns
Tue Aug 14 00:00:00 UTC+0200 2012
I call the code from the web page as follows
$.ajax(
{
url: '#Url.Action("LogsView","Home")',
type: 'POST',
data: { startDate: sDate, endDate: eDate },
success: function(result) { alert(result); },
error: function(param1) { alert(param1); }
});
I have a controller with the following action
public JsonResult LogsView(DateTime startDate, DateTime endDate)
{
var items = FetchItems(startDate, endDate);
return Json(items, JsonRequestBehavior.AllowGet);
}
When I run it, part of the error that is returned is as follows (when vied in fiddler):
The parameters dictionary contains a null entry for parameter 'startDate' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.JsonResult LogsView(System.DateTime, System.DateTime)' ..
I've check my params sent via fiddler and it is as follows startDate=&endDate=
Anyone know how to format and pass in the date correctly (I assume this is where the error lies)?

I needed to add .toJSON() to $("#startDatePicker").datepicker('getDate')
i.e. $("#startDatePicker").datepicker('getDate').toJSON()
if you get an error on the toJSON() function then try
var sd = $("#startDatePicker").datepicker('getDate');
var sDate = $.datepicker.formatDate('dd-MM-yy', sd);

You need to convert the date to string before you send it off to $.ajax() method.

You can this method to convert date to string:
function ShowUTCDate()
{
var dNow = new Date();
var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000);
var utcdate= (utc.getMonth()+1) + '/' + utc.getDate() + '/' + utc.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes();
return utcdate;
}

Related

/Date(1537909200000)/ I having date formatting issue in 'AngularJS'

I can't display the date in the list in json format. How should I follow a path. My angular js knowledge is not good but I need to use it.
HtmlPage
<tbody ng-init="GetAllMatches()">
<tr ng-repeat="m in filteredlist =(matches.data
| filter:filterlist)
| orderBy:sort:reverse
| pagination: currentPage : numPerPage"
ng-if="gamePlayed">
<td>{{m.HomeTeamName}}</td>
<td>{{m.AwayTeamName}}</td>
<td>{{m.StadiumName}}</td>
<td>{{m.Referee}}</td>
<td>{{m.Weather}}</td>
<td>{{ m.StartDate}}</td>
</tr>
</tbody>
.netMVC
var matches = await AppService.MatchService.GetMatchesAsync();
return Json(new { data = matches }, JsonRequestBehavior.AllowGet);
JS
$scope.GetAllMatches = function () {
$http({
method: "GET",
url: "/Match/GetAllMatchAsync"
}).then(function (response) {
$scope.matches = response.data;
}, function () {
alert("error");
});
};
View
/Date(1537909200000)/
Solved
I haven't found any information on your problem, but...
As a solution:
{{m.StartDate.slice(6, -2) | date: 'yyyy-MM-dd HH:mm:ss' }}
Why is your API not returning dates in ISO 8601 format? If you return strings in ISO 8601 format then you just wrap your field function like this
function parseISO8601Date(dateStr) {
return new Date(dateStr);
}
If you really can't change API to return proper ISO 8601 formatted date strings then maybe this blog entry will help you https://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates
Here is if link dies
if (window.JSON && !window.JSON.dateParser) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.dateParser = function (key, value) {
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a)
return new Date(value);
a = reMsAjax.exec(value);
if (a) {
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
}
return value;
};
}
var date = JSON.parse(json,JSON.dateParser);
console.log(date);

Return list of datetimes to drop down using Ajax

I have a drop down list that I need to fill with datetime values passed from an ajax call. The values that populate look like this: "/date1234847269/" and not actual dates. I just need the dates to be passed into the drop down list. I do not need the time stamps that are also in the datetime value that is returned from the controller.
I'm not sure if jQuery has issues with handling c# datetime values and not strings. Any help would be appreciated. Thanks
My View:
<select id="ddlDate" class="form-control bold">
<option value='0'>--Select Date--</option>
</select>
My Ajax Call:
function loadDateDDL(historicalIsChecked, monthlyIsChecked) {
$.ajax({
type: 'POST',
url: '#Url.Action("GetGroupReportDates")',
dataType: 'json',
data: { isMonthly: monthlyIsChecked },
success: function (returnData) {
convertDate(returnData);
$("#ddlDate").empty();
$("#ddlDate").append("<option value='0'>--Select Date--</option>");
$.each(returnData, function (value, key) {
$("#ddlDate").append($("<option></option>")
.attr("value", value).text(key));
});
//alert(returnData);
},
error: function (ex) {
alert('Failed to retrieve dates.' + ex);
}
});
}
function convertDate(returnData)
{
var date = new Date(returnData);
return date;
}
My Controller:
public JsonResult GetGroupReportDates ( Boolean isMonthly )
{
List<DateTime> reportDates = RealmsModel.RealmsAuditDataInterface ( ).GetGroupQueryRptDates ( isMonthly );
return new JsonResult ( )
{
Data = reportDates,
MaxJsonLength = Int32.MaxValue
};
}
Update 1/21/2016:
I am now passing my json data "returnData" to the javascript function below and converting it based on another stack post: How do I format a Microsoft JSON date?
function convertDate(returnData)
{
var date = new Date(returnData);
return date;
}
This now gives me the error "date = Invalid Date {}, returnData = ["/Date(1451628000000)/"]". I feel like I'm getting close. Any help is appreciated.
I resolved this with the following:
function convertDate(returnData)
{
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(returnData);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
The format you're seeing is the old "microsoft" way of formatting dates. There are 2 ways to get around it.
One way would be to use the JSON.Net serialiser instead of the built in JavaScriptSerializer, as it (since version 4.5) formats dates so that they can be automatically parsed.
Another (quicker) way would simply be to extract the numbers from the date in it's current format as pass them to a new javascript Date object.
function toDate(value) {
return new Date(parseInt(/Date\(([^)]+)\)/.exec(value)[1], 10));
}

Run LINQ query with date range check in C# with correct date format

I am getting trouble in running LINQ query and I strongly believe is because of date format. I am getting string values for dates and other tags in ASP.NET C# code-behind webMethod from $ajax jQuery function and I am converting string date to Convert.ToDateTime. Date been selected on web-page using jQWidget and format is coming as in following screen shot of alert
and following screen shot of code-behind debugging
Ajax jQuery Function
$("#ctl00_ContentArea_btnFilterStudent").click(function (e) {
e.preventDefault();
var givenDateFrom = $("#CldBoxStudentFilter_From").jqxDateTimeInput('getDate');
var givenDateTo = $("#CldBoxStudentFilter_To").jqxDateTimeInput('getDate');
if(givenDateFrom && givenDateTo)
{
var selectedFilteredValue = $("#<%=ddLStudentFilterList.ClientID%> option:selected").val();
$.ajax({
url: 'TutorForm.aspx/FilterStudentListInRelationToStaffByDateRange',
type: "POST",
data: JSON.stringify({ GivenStaffID: SelectStaffID, SelectFilterOption: selectedFilteredValue, FromDate: givenDateFrom, ToDate: givenDateTo }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
failure: function (response) {
alert(response.d);
}
}).done(function (response) {
});
C# code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string FilterStudentListInRelationToStaffByDateRange(string GivenStaffID, string SelectFilterOption, string FromDate, string ToDate)
{
string returnList = string.Empty;
bool StudentStaffRelationActive = false;
List<StudentInRelationToStaffModelView> studentStaffRelationObject = new List<StudentInRelationToStaffModelView>();
//var queryList = StaffRelay.GetStudentsForRelationship(Convert.ToInt32(GivenStaffID), Convert.ToDateTime(FromDate), Convert.ToDateTime(ToDate), RelationshipStatus.None);
if (SelectFilterOption.Equals("StudentFilterSelectAll"))
{
var queryList = StaffRelay.GetStudentsForRelationship(Convert.ToInt32(GivenStaffID), null, null, RelationshipStatus.None);
var x = (from b in queryList
where b.RelationshipDateStart >= Convert.ToDateTime(FromDate) && b.RelationshipDateEnd <= Convert.ToDateTime(FromDate)
select b).ToList();
//need help here......
Looks like a time zone issue - client side +1 hour adjusted. You may have to specify the time zone of the date you are expecting on the server side.
DateTime rawDate = Convert.ToDateTime(matchFromXmlSoccer.Date);
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime targetDateTime = TimeZoneInfo.ConvertTime(rawDate, est);

Making a Simple Ajax call to controller in Mvc

I´m new to mvc and I try to to do a simple Ajax call to my controller, so I can use a date- and timepickers in my create view.
I get this error message when I use debugging in IE, but if I do a breakpoint it looks like I got correct data.
The parameters dictionary contains a null entry for parameter 'Lokal' of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult CreateEvent(System.String, System.String,
System.String, Int32)' in
'VLVision.Controllers.SammantradesAdminController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter.Parameternamn: parameters
HTML
script type="text/javascript">
function createSammantrade() {
var sammantrade = document.getElementById('sammantrade').value;
var date = document.getElementById('datepicker').value;
var startTime = date + ' ' + document.getElementById('StartTimepicker').value;
var endTime = date + ' ' + document.getElementById('EndTimepicker').value;
var lokal = document.getElementById('lokal').value;
$.ajax({
url: "#Url.Action("CreateEvent", "SammantradesAdmin")",
data: { createSammantrade: sammantrade, createStartTime: startTime, createEndTime: endTime, createLokal: lokal },
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
$("#clanderDiv").html(data);
$("#setEventResponse").html("Händelse sparad");
// $(".blank").tooltip();
}
});
}
Controller
public ActionResult Create()
{
ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal");
return View();
}
[HttpPost]
public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, int Lokal)
{
Sammantrade sammantrade = new Sammantrade();
sammantrade.sSammantrade = createSammantrade;
sammantrade.sStartTid = Convert.ToDateTime(createStartTime);
sammantrade.sSlutTid = Convert.ToDateTime(createEndTime);
sammantrade.lID = Lokal;
if (ModelState.IsValid)
{
db.Sammantrade.Add(sammantrade);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal", sammantrade.lID);
return View(sammantrade);
}
Since you have different names for the parameter in JS and in C#, it cannot be bound:
data: { createSammantrade: sammantrade, createStartTime: startTime, createEndTime: endTime, createLokal: lokal }
public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, int Lokal)
Either change createLokal to lokal in JS or do vice versa in C# (or bind one name to another).
Your parameter name in json is different from the c# action, these two should match. Change one of those:
either change createLokal : lokal to Lokal:lokal or in your action change parameter name to createLokal in your action
Thanks, it did not work at first. But when I debugged it I saw that the result from lokal was a string I change it to a string and then convert it back to a int.
Now I have some other problems, but I think I can fix the rest.
Sry for my crappy English, but I hope you understand what I mean.
Thanks!

return formatted date from WebMethod to JSON

I have a WebMethod that returns at date {"d":["/Date(1390411800000)/"]}:
[WebMethod]
public static object getBreadCrumbDate(int projectID, int statusID)
{
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var thisId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == projectID && x.StatusID == statusID).Max(x => x.BreadCrumbID);
var columns = myEntities.tbBreadCrumbs.Where(x => x.BreadCrumbID == thisId)
.Select(x => x.CreateDateTime).ToList();
return columns;
}
}
and I want to format it "mmm dd, yy" (Jan 22, 14) and return it to the calling AJAX but not sure the best way. Here's my AJAX:
function getBreadCrumbDate(projectID, statusID) {
$.ajax({
url: "view-requests.aspx/getBreadCrumbDate", // Current Page, Method
data: JSON.stringify({
projectID: projectID,
statusID: statusID
}), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 10000, // AJAX timeout
success: function (result) {
$("#divApprovedStatus").html(result.d[0]);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
Right now it prints out /Date(1390411800000)/ but want it formatted. Is it best to do in the jQuery after the success or in the C# when I return it? Whichever way, I'm not sure how to do it and could use some pointers.
Thanks!
It shows some red lines... do you want me to tell you what they say?
I'd say it's easiest to just do it in C# using ToString([time format]) with the proper format.
Since you have a DateTime? object, known as a Nullable<DateTime>, to access the DateTime value, you have to use the Value property of DateTime? (The Value property exists on all Nullable Types.
For "Jan 22, 14", the format would be as follows:
These are just some generic examples of the syntax:
// DateTime object
someDateTimeInstance.ToString("MMM d, yy");
// DateTime? object
someNullableDateTimeInstance.Value.ToString("MMM d, yy"); // assumes no nulls
// DateTime? object with null check
String formattedDateTime = (null != someNullableDateTimeInstance
? someNullableDateTimeInstance.Value.ToString("MMM d, yy")
: string.Empty);
Additionally, you're using Entity Framework which translates your LINQ statements into SQL.
Basically you have to pull the data first, and then format it. Even though CreateDateTime IS a Nullable<DateTime> column, that entire expression is converted by Linq-To-Entities to SQL. And, Linq-To-Entities doesn't know how to translate the method call .ToString(string format).
By separating the query from the format call, we avoid this issue. You get the data from the entities, and call .ToList() which will cause EF to load the data into memory. Then, you can work with this new list containing DateTime? objects and use the ToString(string format) method to get the formatted dates.
In your code:
[WebMethod]
public static object getBreadCrumbDate(int projectID, int statusID)
{
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var thisId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == projectID && x.StatusID == statusID).Max(x => x.BreadCrumbID);
var columns = myEntities.tbBreadCrumbs
.Where(x => x.BreadCrumbID == thisId)
.Select(x => x.CreateDateTime)
.ToList();
var formattedList = columns
.Select(d => null != d
? d.Value.ToString("MMM d, yy")
: string.Empty) // this is just one example to handle null
.ToList();
return formattedList;
}
}
if you can use datepicker then you could define a JavaScript function
getDateFromJson: function(jsonDateString, languageCode) {
return $.datepicker.formatDate($.datepicker.regional[languageCode].dateFormat, new Date(parseInt(jsonDateString.substr(6), 10)));
}
and then you could define a i18n file for the datepicker as
jQuery(function ($) {
$.datepicker.regional['en-us'] = {
closeText: 'Done',
prevText: 'Prev',
nextText: 'Next',
currentText: 'Today',
monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
weekHeader: 'Wk',
dateFormat: 'mm/dd/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['en-us']);
});
//German
jQuery(function($){
$.datepicker.regional['de'] = {
closeText: 'schließen',
prevText: '<zurück',
nextText: 'Vor>',
currentText: 'heute',
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
weekHeader: 'KW',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['de']);
});
So you could define your language and your dateFormat for it.
Now when you need a Date, just call this function
getDateFromJson(result.d[0], 'en-us'); //for USA Date
getDateFromJson(result.d[0], 'de'); //for German Date
Hope this points you in the right direction!

Categories

Resources