res.json({data: new Date()});
This is the response: {data: '2014-05-20T01:40:34.993Z'}
How to configure express to return timestamp instead of date string?
{data: 1343235454545}
You need to use Date.now()
Example - res.json({data: Date.now()});
Then you will get result in timestamp "data": 1404359477253 likewise.
This worked out perfectly to filter all Date
app.set('json replacer', function (key, value) {
if (this[key] instanceof Date) {
// Your own custom date serialization
value = this[key].now();
}
return value;
});
You can use moment.js (as suggested by #swapnesh). But I found it more suitable to simply save the data as a timestamp. Since I'm using mongoDB I'm using Number for the data type.
So my schema looks something like this:
var myDataSchema = {
start: {type: Number, required: "myDataSchema.start is a required field"},
}
This will output:
{
"_id": "564c6828d4f028236cf1a6c8",
"start": 1450969200
}
`
Schema:({title:String},{timestamps:true})
`you can true the timestamps inside the model. I think problem solved
Related
I'm hoping that someone can please help with FullCalendar (v4) not loading events when using the Json option. It works fine when the same data is hard coded as an event.
The Json produced is valid - i.e. it validates with https://jsoncompare.com
I've spent an enormous amount of time trying to figure this out myself and I've hit a wall - so time to ask for help.
I've tried using the built in Net Json serializer - but this produces the wrong date format, so I've also tried newtonsoft Json.net, which does produce the correct date format for FullCallendar but still will not load events.
There are no JS console errors when using the JSON, it simply does not load into the calendar. The JSON is coming from the same domain (i.e. not affected by cross domain issue).
Any help/advice would be most welcome, thank you.
THIS WORKS PERFECTLY, WHEN THE EVENTS ARE HARDCODED:
var calendar = new FullCalendar.Calendar(calendarEl,
{
plugins: ['interaction', 'dayGrid', 'timeGrid'],
defaultDate: new Date(),
defaultView: 'timeGridWeek',
minTime: '07:00:00',
maxTime: '22:00:00',
timeZone: 'local',
header: {
left: 'prev,next today',
center: 'title',
right: 'timeGridDay,timeGridWeek,dayGridMonth'
},
events: [ //hardcoded events load just fine
{
id: '12',
title: 'Event Name',
start: '2019-08-28T08:00:00',
end: '2019-08-28T08:30:00'
}
]
});
calendar.render();
}
WHEN USING THE JSON OPTION, IT DOES NOT WORK:
//JSON provided events do not load
events: {
url:'/CourseTimetable/GetAllEventsAsJson'
}
ALTERNATIVE WAY OF PROVIDING FEED (without braces and "url:" prefix):
events:'/CourseTimetable/GetAllEventsAsJson'
THE URL WORKS FINE - validates as JSON - AND DOES NOT GENERATE ANY ERRORS - IT PRODUCES:
"[{\"id\":12,\"title\":\"Event 1\",\"start\":\"2019-08-29T08:00:00\",\"end\":\"2019-08-29T08:30:00\"}]"
HEADER and cors info:
Content-Type: application/json; charset=utf-8
Referer: http://localhost:54928/CourseTimetable
Request Method: GET
Status Code: 200 OK
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
Thanks in advance for any help/advice :)
Here are the two alternative controller versions (with standard .net and then with json.net)
Standard .net
public JsonResult GetAllEventsAsJson(DateTime? start = null, DateTime? end = null)
{
var events = db.CourseTimetables.Where(p => p.StartTime >= start && p.EndTime <= end)
.Select(s => new
{
id = s.Id,
title = s.Title,
start = s.StartTime,
end = s.EndTime
}).ToList();
//using built in .NET serialiser
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
OUTPUT FROM ABOVE ACTION (main difference being the outputted dates and escaping):
[{"id":12,"title":"Event 1","start":"\/Date(1567062000000)\/","end":"\/Date(1567063800000)\/"},{"id":13,"title":"Event 2","start":"\/Date(1567148400000)\/","end":"\/Date(1567150200000)\/"}]
Json.Net version
public ActionResult GetAllEventsAsJson(DateTime? start = null, DateTime? end = null)
{
var events = db.CourseTimetables.Where(p => p.StartTime >= start && p.EndTime <= end)
.Select(s => new
{
id = s.Id,
title = s.Title,
start = s.StartTime,
end = s.EndTime
}).ToList();
//USING JSON.NET
string jsonData = JsonConvert.SerializeObject(events);
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
OUTPUT FROM ABOVE ACTION (dates are in correct iso format with this):
"[{\"id\":12,\"title\":\"Event 1\",\"start\":\"2019-08-29T08:00:00\",\"end\":\"2019-08-29T08:30:00\"},{\"id\":13,\"title\":\"Event 2\",\"start\":\"2019-08-30T08:00:00\",\"end\":\"2019-08-30T08:30:00\"}]"
This format: "[{\"id\":12,\"title\":\"Event 1\",\"start\":\ ...etc is the problem. You're double-serialising the data. See those outer quote marks (") and slashes \? The outer quote marks indicate that you are returning a simple string as the response (which is valid JSON, but will be treated as plain text by the parser), and the slashes are the result of having to escape the quote marks within the string. Thus the inner data, while it looks like JSON, is not treated as JSON by the client-side parser. Instead the whole thing is just treated as one big string, with no objects, properties etc within it.
In ASP.NET MVC, return Json... expects you to supply it with an object. It will then automatically serialise that to JSON for you. You don't need to serialise it before you pass it in. Just remove that code and send events directly to the Json() method:
public ActionResult GetAllEventsAsJson(DateTime? start = null, DateTime? end = null)
{
var events = db.CourseTimetables.Where(p => p.StartTime >= start && p.EndTime <= end)
.Select(s => new
{
id = s.Id,
title = s.Title,
start = s.StartTime,
end = s.EndTime
}).ToList();
return Json(events, JsonRequestBehavior.AllowGet);
}
P.S. What version of MVC are you using? The more recent, supported versions use JSON.NET as the default serialiser anyway, so there should be no reason to have to do it manually. If you have an older version of MVC (which it looks like you might have since it's producing those odd date formats e.g. Date(1567062000000)\) and cannot upgrade for some reason, there are ways to make it use JSON.NET by default. Alternatively, you could do the serialisation yourself using JSON.NET, and then just return a plain string from your action method.
P.P.S. Another alternative to the above is to use the momentJS plugin in fullCalendar which then allows you to use momentJS to parse your dates - and momentJS includes the ability to parse ASP.NET's old date format.
I am using fullCalendar in my MVC project. I downloaded fullCalendar from Nuget but it doesn't display my data on the calendar. I can get my data but it is not displaying.
What is going wrong in my code?
MVC action method:
public JsonResult GetEvents()
{
dbContext = new Context();
var events = dbContext.Schedule.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
View:
I think the GenerateCalendar function is not working.
<link href="~/Content/fullcalendar.min.css" rel="stylesheet" />
<script src="~/Content/PanelJS/jquery.min.js"></script>
<script src="~/Content/PanelJS/moment.min.js"></script>
<script src="~/Scripts/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url:"#Url.Action("GetEvents","Schedule")",
success: function (data) {
$.each(data,function(i,v)
{
events.push({
title: v.Name,
start: v.Date,
end: v.EndDate,
location:v.Location
});
console.log(events);
})
GenerateCalendar(events);
},
error:function(error)
{
alert('Error');
}
});
function GenerateCalendar(events)
{
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar(
{
contentHeight: 400,
defaultDate: new Date(),
color:'lightBlue',
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right:'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events:events
})
}
});
</script>
Console result ;
end: "10/05/2018 "location: "Chicago" start: "09/05/2018" title: "MyEvent"
From the console output it looks like your dates are being supplied as strings in an ambiguous format. fullCalendar / momentJS will not understand that without being explicitly told what you format is being used. It could be dd/mm/yyyy or mm/dd/yyyy. There is no way for the parser to know what to do with it.
Therefore fullCalendar will not be able to use this data as an event, because it doesn't understand the start and end dates.
The date and time formats accepted by fullCalendar are the same as those accepted by momentJS (since it uses momentJS to work with dates). This is documented here: https://fullcalendar.io/docs/moment and in more detail here: http://momentjs.com/docs/#/parsing/
Therefor, you can either
1) (recommended) Re-write your server-side code so that it returns dates in ISO format. Generally if you are using DateTime objects in your C# code, then the .NET JSON serialiser will do that for you automatically. Since you're directly serialising the result of an Entity Framework query into JSON, then I would suspect that the Date and EndDate properties of your Schedule class are strings rather than DateTimes, which in turn means that you may be storing dates as strings within your database. If so, that is a bad practice which you should fix immediately by storing dates as datetime columns. Dates are not strings, they are dates. What you see on screen (e.g. 09/05/2018) is merely one of many possible representations of that date in a human-readable form. It is not a good format for actually storing the date information.
OR
2) (alternative) If that's not the case, or not possible for some reason, then tell momentJS to parse the dates according to the format you're supplying and then pass the data to fullCalendar as a moment object, e.g.
events.push({
title: v.Name,
start: moment(v.Date, "DD/MM/YYYY"),
end: moment(v.EndDate, "DD/MM/YYYY"),
location: v.Location
});
In-depth documentation of the format-specific parsing functionality in momentJS can be found here: http://momentjs.com/docs/#/parsing/string-format/
Here you can see the binding for a kendo ui grid:
<div data-role="grid" data-bind="source: reportSource, visible: reportVisible"
data-columns='[{"field":"TIME", "title": "TIME", format: "{0:yyyy-MM-dd hh:mm:ss}", parseFormats: ["yyyy-MM-dd'T'HH:mm:ss"]}, {"field":"LOGIN", "title": "LOGIN"}, {"field":"DEAL", "title": "DEAL"}]'>
</div>
As you see I'm trying to parse dates. I found this solution but when I try to apply this in mvvm binding, the single quotes of 'T' char cause trouble.
How can I parse dates in mvvm binding?
Thanks in advance,
Here is the jsfiddle to solve the problem: http://jsfiddle.net/BYqpL/3/
The key point is:
The build-in dataSource data parsing is executed only when the data comes from a transport
and also we have to define the parse method for the field in schema.
"CreatedDate": {
type: "date",
parse: function(value) {
return kendo.parseDate(value, "yyyy-MM-ddTHH:mm:ss");
}
}
Since you are dealing with an attribute, try replacing your single quote with
'
I was having the same issue and this article helped me alot
http://blog.falafel.com/passing-dates-kendo-ui-aspnet/
Changes i made in my code:
in parameterMap
if (operation === "update" || operation === "create") {
data.model_date_field = kendo.toString(kendo.parseDate(data.model_date_field), "G");
return data;
}
in model definition
fields: {
model_date_field: { nullable: true, type: "date" }
}
I'm looking to leverage sequelize on a big project, and was hoping I could use it to store a JSON Object as a property in a Model.
I feel like I'm struggling with this, but perhaps I'm missing something simple?
I'm defining a model (Context) as follows:
var contextProperties = {
contextName: { type: Sequelize.STRING, validate: { is: ["[a-z]",'i'], notEmpty: true } },
_trackList: {type: Sequelize.TEXT},
trackList: {type: Sequelize.TEXT}
}
var contextGetSet = {
getterMethods: {
trackList: function(){
return JSON.parse(this._trackList);
}
},
setterMethods: {
trackList: function(v){
this._trackList = JSON.stringify(v);
}
}
};
var Context = sequelize.define('Context', contextProperties, contextGetSet);
Now when I create my Context, it seems to work before I save.
var contextMain;
Context.create({contextName: "Whatever"}).success(function (context){
contextMain = context;
contextMain.trackList = { atrackList: "1111", anotherTrackList: 2872 };
console.log(constextMain.trackList);
//logs { atrackList: "1111", anotherTrackList: 2872 } as expected
contextMain.save().success(function (contextSaved){
console.log(contextSaved.values);
//all values are null except for the contextName
});
});
So the JSON IS setting right, but the object returned by the save().success() method does not seem to have the proper values of what I set it to.
When I log the object returned by the save().success() method (ie. contextSaved.values) the object looks like this:
{ contextName: 'Whatever',
_trackList: 'null',
trackList: null,
id: 6,
createdAt: Fri Dec 06 2013 15:57:39 GMT-0500 (EST),
updatedAt: Fri Dec 06 2013 15:57:39 GMT-0500 (EST)
}
Everything is null!!
Even more weird is that when I look at the save SQL query made to save contextMain, it seems to be saving right!
Executing: UPDATE "Contexts" SET "contextName"='Whatever', "_trackList"='{"atrackList":"1111","anotherTrackList":2872}', "trackList"=NULL,"id"=7, "createdAt"='2013-12-06 20:59:39.278 +00:00', "updatedAt"='2013
-12-06 20:59:39.294 +00:00' WHERE "id"=7 RETURNING *
Notice that: "_trackList"='{"atrackList":"1111","anotherTrackList":2872}'
Also when I look at the actual SQL row for it, it does have the stringified JSON object in there!
If I load the Context using sequelize though...
Context.findAll().success(function(contexts) {
console.log(JSON.stringify(contexts))
// also displays null for _trackList and trackList
});
So very strange. Any help greatly greatly appreciated!!
Thanks so much! Sorry this post is so long!
This was apparently a bug with the getters and setters for the objects and resolved recently:
https://github.com/sequelize/sequelize/issues/759
Can you check if the setterMethod that is running JSON.stringify is getting called? Maybe its trying to insert as an object not a string?
More broadly, have you considered MongoDb? There may be other reasons why it isn't appealing for you, but just from this glimpse into the project, it looks like it would have real advantages--chiefly not having to parse json in both directions... but beyond that you'd be able to do things like query with the values inside that object, which might prove useful later on.
I just working with JSON data and am playing around with jQuery and Ajax requests. Pretty basic stuff, but here's my problem.
I have a basic data set which I was using for time tracking. I know how to parse the simple JSON data like this:
{
"end" : "1/18/2011",
"start" : "1/18/2011",
"task" : "Code Review",
},
It's the more complicated stuff I'm trying to parse like this where I'm trying to pull the "time" data out.
{
"end" : "1/17/2011",
"start" : "1/17/2011",
"task" : "Exclusive Brands",
"time" : {
"analysis" : 4,
"documentation" : 3,
"meetings" : 2
}
This is the code for the script I've been using to parse the simple data:
$(function() {
$('.load').click(function(){
$.getJSON("data.js",function(data){
$.each(data.timesheet, function(i,data){
var div_data ="<div class='box'>"+data.start+" "+data.task+"</div>";
$(div_data).appendTo("#time-tracking");
});
}
);
return false;
});
});
My question is what's the format to parse the time data, or what's the best way to parse the information nested inside the time element?
Any help will be greatly appreciated.
A JSON string will be parsed into an object. When parsed, the time is the key of one object. You could retrieve the value of this object through the dot operator (.).
data = JSON.parse('{"end":"1/17/2011", "start":"1/17/2011", "task":"Exclusive Brands", "time": {"analysis":4, "documentation":3, "meetings":2 } }')
// => obj
data.time.analysis
// => 4
In your case similarly you could use the data.time.meetings to access your data from remote server.
Unless I am terribly mistaken, since jquery already converted data into a javascript for you, you should be able to access time as if it was a javascript object like so:
var analysis = data.time.analysis;
var documentation = data.time.documentation;
var meetings = data.time.meetings;
etc...