conversion of date and time into another format in full calendar - c#

I am working ion full calendar in c# MVC .a need to read dates from database .but I can't read them in proper mode by using JSON thus I need to convert dates to following format...
Current Output Format:2014-06-01 16:00
[{"id":"d719381c-b3e4-e311-afa9-eca86bf6cf86","title":"Annual Function","start":"2014-06-01 16:00","end":"2014-06-01 19:00"},{"id":"d719381c-b3e4-e311-afa9-eca86bf6cf86","title":"convocation day","start":"2014-06-24 00:49 12:49","end":"2014-06-24 "}]
Required output Format : "/Date(1423087200000)/"
[{"id":1259,"title":"bvbvcbc","start":"/Date(1423845000000)/","end":"/Date(1423931400000)/","allDay":false,"description":"Notesbvbvcbc"},{"id":1263,"title":"om nmh sivaay ","start":"/Date(1423087200000)/","end":"/Date(1423432800000)/","allDay":false,"description":"Notesom nmh sivaay "},{"id":1265,"title":"vimal raturi","start":"/Date(1423546200000)/","end":"/Date(1423632600000)/","allDay":false,"description":"Notesvimal raturi"}

You would have to use Date() method to get the unix timestamp.
var ob = [
{"id":"d719381c-b3e4-e311-afa9-eca86bf6cf86","title":"Annual Function","start":"2014-06-01 16:00","end":"2014-06-01 19:00"},
{"id":"d719381c-b3e4-e311-afa9-eca86bf6cf86","title":"convocation day","start":"2014-06-24 00:49","end":"2014-06-24 12:49"}
];
for (var i = 0; i < ob.length; i++ ){
var unix_start = new Date(ob[i].start);
var unix_end = new Date(ob[i].end);
ob[i].start = '/Date(' + unix_start.getTime() /1000 + ')/';
ob[i].end = '/Date(' + unix_end.getTime() /1000 + ')/';
}

thanks for your answers,
i found the answer by simply writin g following code in my view under the ajax success property,
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});

Related

How to get the current date in DataTable.Compute

I am trying to compute the string expression by DataTable.Compute.
A simple string like below is working:
static void Compare()
{
var logicalExpression = "'2022-09-14' <= '2029-12-31'";
DataTable dt = new DataTable();
var result = (bool)dt.Compute(logicalExpression, "");
}
But, the date 2022-09-14 is dynamic, it should be the date for now.
I have tried to replace '2022-09-14' with Now(),GETDATE(). None of them work.
Is there any function to get current date time in Compute?
You can do this like this:
var logicalExpression = "'" + DateTime.Now.ToShortDateString() + "' <= '2029-12-31'";
you can also specify in what format you want the date, see this post for an example.
var logicalExpression = $"#{DateTime.Now:MM/dd/yyyy}# <= #12/31/2029#";
This is the proper way to represent dates in this context. See here for more information.

Fullcalendar 2.5 eventSource url appends start and end date incorrectly formatted

So I'm in the process of upgrading fullcalendar from 1x to 2x in an AngularJS application and I'm running into some issues where the eventSource url needed to gather the calendar events is appending the start and end param dates formatted as (YYYY-MM-DD) when it needs to be in seconds--I think--at least that's what we had in version 1x which was working.
When my controller is instantiated the first thing I do is establish the eventSources variable needed to pass into the fullcalendar directive (I'm using the angular fullcalendar wrapper directive: http://angular-ui.github.io/ui-calendar/).
HTML:
<div id="calendar" class="col-sm-9" ng-model="eventSources" calendar="myCalendar" config="uiConfig.calendar" ui-calendar="uiConfig.calendar"></div>
Controller:
$scope.eventSources = [];
for (var i = 0; i < calendars.length; i++) {
$scope.eventSources[i] = getEventSource(calendars[i]);
}
var getEventSource = function(calendar) {
return {
cid: calendar.cal_head_id,
url: "/api/classroom/student/calendar?ids=" + calendar.cal_head_id,
className: 'calendar-' + calendar.sort_order,
backgroundColor: calendar.color_code
};
};
However my string param keeps coming out as:
ids=2525213&start=2015-11-30&end=2016-01-11&_=1449868998385
And finally my server side code to handle the request:
[ActionName("calendar")]
public JsonArray GetCalendarEvents(string ids, int start, int end)
{
var calendars = ids.Split(',');
var startDate = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(start);
var endDate = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(end);
var data = new CalendarService().GetEvents(calendars, 0, startDate, endDate);
var events = new JsonArray();
var results = (JsonArray) data["results"];
foreach (JsonObject obj in results)
{
var name = ((JsonString) obj["name"]).Value;
if (name == "<b>Homework</b>")
{
name = "<img src=/images/icons/house.png /> Homework";
}
var link = ((JsonString) obj["link"]).Value;
if (!string.IsNullOrEmpty(link) && link.Contains("doEditEvent"))
{
link = "";
}
var eventStart = Convert.ToDateTime(obj["start_time"].ToString());
var eventEnd = Convert.ToDateTime(obj["end_time"].ToString());
events.Add(new JsonObject
{
{"id", obj["event_id"]},
{"calId", obj["calendar_id"]},
// Note: Firefox requires the dates are in the below format - JD 6/12/2013
{"start", eventStart.ToString("o")},
{"end", eventEnd.ToString("o")},
{"allDay", eventStart == eventEnd.AddMinutes(1).AddDays(-1)},
{"title", name},
{"link", link},
{"description", obj["description"]}
});
}
return events;
}
The problem with manually adding the start and end is that fullcalendar does this by default, so it concatenates the params multiple times. According to the documentation on upgrading from 1x to 2x (http://fullcalendar.io/wiki/Upgrading-to-v2/) the library was updated to use moment, which is great because I assumed that would fix any formatting issues, and I definitely have that included in my project.
I'm looking for a solution here that's not going to involve me tampering with the fullcalendar source code hopefully, otherwise I'll need to go back to 1x.
The startParam and endParam changed from v1 to v2, from UNIX timestamp to ISO8601 style date string. You will have to either add additional parameters containing timestamp, hack fullcalendar.js to send timestamp, rework your server side code, or use v1.xx
For your server side code, seems like you could change it to
[ActionName("calendar")]
public JsonArray GetCalendarEvents(string ids, string start, string end)
{
var calendars = ids.Split(',');
var startDate = DateTime.parse(start);
var endDate = DateTime.parse(end);
If you want to override the 'start' and 'end' to be UNIX stamps this could work.
See fiddle here
$('#calendar').fullCalendar({
/* You can rename the start and end params from 'start' and 'end' */
/* In this code, 'start', 'end' and 'startDate' and 'endDate' will be on URL */
startParam: 'startDate',
endParam: 'endDate',
eventSources: [{
url: '/test', /* Set this to whatever is appropriate */
data: function() {
var view = $('#calendar').fullCalendar('getView');
return {
/* Then you can change 'start' and 'end' in the URL to be UNIX stamps */
'start': view.start.unix(),
'end': view.end.unix(),
};
},
/* This is just to demo the URL being queried, not required */
beforeSend: function () {
alert(this.url);
}
}]
});

Retrieving data from a List<T> and putting it in a dropdown list using Jquery

I have retrieved data from the database and put it in a List. I need to access this list of items using Jquery and put them in a dropdown list. Here is my code in the Controller
//filling list with data from data reader
List<Object> list=new List<Object>();
while (read.Read())
{
var var1 = (int)read["dbColumn"];
var var2 = (string)read["dbColumn2"];
list.Add(var1);
list.Add(var2);
}
var serializer=new System.Web.Script.Serialization.JavaScriptSerializer();
string theData = serializer.Serialize(list);
return theData;
In my jquery I have this
if (!$.isEmptyObject(data))
{
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i].dbColumn];
var second = [data[i].dbColumn2];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html("<option>"+html+"</option>").show();
}
Then I have this as the Html code where I want the list to be displayed
<select id="SelectBox"></select>
When I try this, I get a looooooong list of empty option fields. What could be the issue
Don't wrap content of select control in <option>.
$('#SelectBox').html(html).show();
You are just returning a serialized List<Object> so there isn't a dbColumn1 or dbColumn2 in your result.
It might be worth creating a wrapper class or using a Dictionary<int, string> for your results but to make it work using your current code you can change your jQuery code to:
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i]];
var second = [data[++i]];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html(html).show();
Note that for the second value we are just incrementing i to get to the next item in the list. We are also just using the value from data[i] directly rather than trying to access any properties from it as it is just an array of items.
This gives a select box populated something like this:
Edit
It would seem from the comments that the Json being returned is not being parsed correctly as well as having your indexing and naming incorrect as per the above. Assuming you are using the jquery.ajax() method to retrieve the Json it is probably treating the returned item as a string. From the documentation on the dataType parameter (emphasis mine):
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
You could change your call to pass dataType: 'json' and as per the documentation jQuery will automatically parse it into a JavaScript object:
ajaxReq = $.ajax({
url: '/home/something',
dataType: 'json', //get jQuery to parse the response for us
success: function (data) {
//data is now a parsed JS object
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i]];
var second = [data[++i]];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html(html).show();
}
});
If you want to parse the json manually or you are using a different method to retrieve the results you could parse the json yourself by adding
data = JSON.parse(data);
before the line var len = data.length;
var batch= document.getElementById('id');
$(batch).append($("<option></option>").val(first ).html(second ));
Note :Id get using browser.ie(insepect element).

ViewBag on a Javascript code mvc 4

I am having a trouble doing this: I have a ViewBag that contains the list of documents Id's and the response time for each one, created like this:
Controller:
ViewBag.Documents= (from n in db.DocumentType
select new {a = n.DocumentTypeId, b=n.ResponseTime});
Based on the document that the user selected on a dropdownlist, the javascript code calculates the real duration of processing the document (duration).
DocumentId(int) Response(int)
1 2 days
2 3 days
3 1 day
The complete javascript code calculates the final date based on response time without weekends and holidays, but the only part that it is not working is the following part of JavaScript code:
JavaScript at the view:
function CalculateTime(documenttype) {
var duration= 0;
var jScriptArray= new Array();
var array = '#Html.Raw(Json.Encode(ViewBag.Documents))';
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < 2; j++) {
jScriptArray [i][j] = array [i][j];
}
}
for (i = 0; i < jScriptArray.length; i++) {
if (documenttype== jScriptArray [i][0]) duration= jScriptArray [i][1];
}
return duration;
}
I already have the correct documenttype variable based on a dropdownlist but this script is not working. I think is the way I want to use the ViewBag, but I am not pretty sure. What I need to know is: what is wrong with my code or another way to do this.
Thanks in advance
Just remove quotes
var array = #Html.Raw(Json.Encode(ViewBag.Documents));
Just remove the quotes(') and you have to Newtonsoft.Json for this.
var array = #Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Documents);
This will work.
A friend of mine helped me solve my problem. Some of you told me to use Json, so we did this:
Controller:
using System.Web.Script.Serialization;
using Newtonsoft.Json;
...
var timeList= db.DocumentType.ToList();
ViewBag.ResponseTimes= new JavaScriptSerializer().Serialize(
JsonConvert.SerializeObject(new
{
times= (from obj in timeList
select new { DocumentTypeId= obj.DocumentTypeId, ResponseTime= obj.ResponseTime})
}, Formatting.None));
JavaScritp at the View:
function CalculateTime(documenttype) {
var duration = 0;
var jScriptArray = new Array();
var array = $.parseJSON(#Html.Raw(ViewBag.ResponseTimes));
for (i = 0; i < array.times.length; i++) {
if (parseInt(documenttype) == array.times[i].DocumentTypeId) {
duration= array.times[i].ResponseTimes;
}
}
return duration;
}
Thanks!
PS: I don't know which of both answers give the acceptance cause we used part of both....

String was not recognized as a valid DateTime - Whats wrong?

I have been getting an annoying littler error and cannot for the life of me figure out why it is being cause. I have an xml file where i am storing data, as shown below.
- <EmployeeFinance>
<EmployeeEmploy_Id>5584</EmployeeEmploy_Id>
<EmpPersonal_Id>30358</EmpPersonal_Id>
<No_DaysWorked>30</No_DaysWorked>
<Date_Appointment>17/02/2012</Date_Appointment>
<Date_Employment>02/05/1984</Date_Employment>
<Date_Termination>01/01/0001</Date_Termination>
<Payperiod_StartDate>01/01/2013</Payperiod_StartDate>
<Payperiod_EndDate>31/01/2013</Payperiod_EndDate>
<BatchNumber>38</BatchNumber>
<PAYE_ToDate_Computed>0</PAYE_ToDate_Computed>
<Income_Tax_RateID>0</Income_Tax_RateID>
<NIS_RateID>0</NIS_RateID>
<NIS_weeks_worked>0</NIS_weeks_worked>
</EmployeeFinance>
If you look at the date nodes, Payperiod_StartDate,Payperiod_EndDate, Date_Appointment etc. They all have the same format. Now in my C# code, when i write my query to select from the xml file i get the String was not recognized as a valid DateTime error. WHen i comment out all the other dates and leave start_date, it works. They are the same format , i cant see what i am doing wrong. Please help me.
var context = new SSPModel.sspEntities();
XElement xelement = XElement.Load(GlobalClass.GlobalUrl);
XDocument doc = XDocument.Load(GlobalClass.GlobalUrl);
var query = from nm in xelement.Elements("EmployeeFinance")
select new EmployeeEmploy
{
Employee_Personal_InfoEmp_id = (int)nm.Element("EmpPersonal_Id"),
Substantive_designation = (int)nm.Element("Position_Id"),
Grade_Id = (int)nm.Element("Grade_Id"),
PositionTotal_PtBasic = (double)nm.Element("Sum_AllPosition"),//part of basic
GradeTotal_PtBasic = (double)nm.Element("Sum_AllGrade"), //part of basic
Housing_Allowance = (double)nm.Element("Housing"),
Base_Pay = (double)nm.Element("Base_Pay"),
startDate = (DateTime)nm.Element("Payperiod_StartDate"),
endDate = (DateTime)nm.Element("Payperiod_EndDate"),
Date_of_Appointment = (DateTime)nm.Element("Date_Appointment"),
Date_of_Employment = (DateTime)nm.Element("Date_Employment"),
Termination_date_actual = (DateTime)nm.Element("Date_Termination"),
Base_Pay_Currency = (string)nm.Element("Currency"),
Exchange_rate = (double)nm.Element("Exchange_Rate")
};
var x = query.ToList();
foreach (var xy in x) {
Debug.WriteLine(xy.endDate);
}
Because 17/02/2012 is not a valid date, however, 02/17/2012 is. The date will be parsed as mm/dd/yyyy. One option is to use DateTime.ParseExact to parse a date with the dd as the first set of numbers. e.g.
var startDate = DateTime.ParseExact("17/02/2012", "dd/MM/yyyy", null);
The debugger will show you that nm.Element("Payperiod_EndDate").ToString() gives you a string that includes the xml tags for that element. Try the following instead:
startDate = DateTime.ParseExact(nm.Element("Payperiod_EndDate").Value, "dd/MM/yyyy", null)

Categories