I''m using EF to query the database using anonymous type.
here the code I use for EF
public JsonResult OverdueEventsCustom()
{
var eventCustomOverdue = _eventCustomRepository.FindOverdueEventsCustom();
return Json(eventCustomOverdue, JsonRequestBehavior.AllowGet);
}
public IQueryable<dynamic> FindOverdueEventsCustom()
{
DateTime dateTimeNow = DateTime.UtcNow;
DateTime dateTomorrow = dateTimeNow.Date.AddDays(1);
return db.EventCustoms.Where(x => x.DateTimeStart < dateTomorrow)
.Select(y => new { y.EventId, y.EventTitle, y.DateTimeStart});
}
Inspecting using the debugger I see the properties is in this format
Date = {16/08/2012 00:00:00}
The resultfor the JSON is
[{
"EventId": 1,
"EventTitle": "Homework Math",
"DateTimeStart": "\/Date(1345108269310)\/"
}, {
"EventId": 4,
"EventTitle": "Homework help with Annie",
"DateTimeStart": "\/Date(1345108269310)\/"
}, {
"EventId": 6,
"EventTitle": "Physic laboratory",
"DateTimeStart": "\/Date(1345108269310)\/"
}]
I need the the json in this format
"DateTimeStart": "(16/08/2012)"
Any idea what i'm doing wrong here? thanks for your help
Related articles
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
How do I format a Microsoft JSON date?
"\/Date(1345108269310)\/" is the correct way to pass a Date to javascript. The way I see it, you have two options here:
If you do not explicitly need the value as a date, you could just pass a string to the JSON variable, containing the pretty-printed date.
Something along the lines of:
DateTimeStart: String.Format("{0: dd-MM-yyyy}", myDate)
If you will still need to use the variable a a date in javascript (for calculations for example), the most consice and readably way would be to create a javascript function that converts said date into the pretty-printed string you want (I don't know if such a function already exists. It isn't too hard to create though:
function prettyDate(date) {
return date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear();
}
I would suggest passing it along as a string from you code behind, as it is more readable. But that only works if you do not need to use the date except for displaying.
Related
I am using react JS to fetch some data from and API endpoint and then display it.
I want to sort it by date and time before displaying it.
Data looks like this when it's fetched:
{
"2021-03-09T07:47:24.897Z[UTC]": "Something happened",
"2021-03-09T07:48:12.256Z[UTC]": "Test event",
"2021-03-09T08:04:49.484Z[UTC]": "Warning",
"2021-03-09T07:08:15.714Z[UTC]": "Test event 2",
"2021-03-09T07:47:24.736Z[UTC]": "Something bad happened 2"
}
I cannot change this json structure. I need to sort this by date and time and display in this format YYYY-MM-DD h:mm:ss
My function to do this looks like this:
formatDate(obj) {
return Object.keys(obj).sort((a,b) => moment(a.obj).format('YYYY-MM-DD h:mm:ss') - moment(b.obj).format('YYYY-MM-DD h:mm:ss'))
}
Then I do the following to the fetched json object:
console.log(this.formatDate(json));
Doing so returns the following:
0: "2021-03-09T07:47:24.897Z[UTC]"
1: "2021-03-09T07:48:12.256Z[UTC]"
2: "2021-03-09T08:04:49.484Z[UTC]"
3: "2021-03-09T07:08:15.714Z[UTC]"
4: "2021-03-09T07:47:24.736Z[UTC]"
Returned dates are not sorted. How do I make sure these returned sorted?
There is no obj property in your json.
There is no need to apply format, as the value becomes String. We can just compare the moment object.
The "[UTC]" inside the key is not standard date format, which leads to warning
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
You may try following snippet which fix above points:
$(function () {
let json = {
"2021-03-09T07:47:24.897Z[UTC]": "Something happened",
"2021-03-09T07:48:12.256Z[UTC]": "Test event",
"2021-03-09T08:04:49.484Z[UTC]": "Warning",
"2021-03-09T07:08:15.714Z[UTC]": "Test event 2",
"2021-03-09T07:47:24.736Z[UTC]": "Something bad happened 2"
};
console.log("Sorted result:");
console.log(formatDate(json));
});
// better to name it as sortDate
function formatDate(obj) {
return Object.keys(obj).sort((a,b) => moment(a.replace("\[UTC\]","")) - moment(b.replace("\[UTC\]","")));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It's unclear by your function if you want to format a date, or sort it like your question asks, but you can directly compare datetime strings for the sorting, i.e. dateA.localeCompare(dateB).
Object.fromEntries(
Object.entries(data).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
);
Convert the object into an array of key-value pairs and sort the array by the key values, then convert the array of key-value pairs back into an object.
If you need to do any format conversions then you should do this via a map operation, i.e. you map an array of keys from one format to another.
To convert to a UTC time:
moment.utc(key.replace("[UTC]", "")).format('YYYY-MM-DD h:mm:ss')
const data = {
"2021-03-09T07:47:24.897Z[UTC]": "Something happened",
"2021-03-09T07:48:12.256Z[UTC]": "Test event",
"2021-03-09T08:04:49.484Z[UTC]": "Warning",
"2021-03-09T07:08:15.714Z[UTC]": "Test event 2",
"2021-03-09T07:47:24.736Z[UTC]": "Something bad happened 2"
};
const sortedData = Object.fromEntries(
Object.entries(data).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
);
console.log(sortedData);
const mappedData = Object.fromEntries(
Object.entries(sortedData).map(([key, value]) => [
moment.parseZone(key.replace("[UTC]", "")).format('YYYY-MM-DD h:mm:ss'),
value
])
);
console.log(mappedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am able to fetch the date from the API but unable to fetch the time and I want to display date and time beside the message. If i receive any message then it should show "today 02:21 pm" else for earlier messages it should display "11-09-2019 06:01 am".
Json data that i received through the api:
[
{
"id": "14526fgy",
"message" : "Hello",
"messageime" : "2019-11-12T03:07:58.359"
},
{
"id": "14546fgy",
"message" : "Hi",
"messagetime" : "2019-12-12T10:07:58.359Z"
}
]
I've attached an example inorder to display date and time. can anyone help me with this?
First you need to split the date from the API by the T ,
let dateSplit = result[0].messagedateTime.split("T");
Now you have an array with 2 elements ['2019-11-12','03:07:58.359']
SO first you need to create a variable (e.g todayDate) that contains todays date in the format of the above ie YYYY-MM-DD . You can get from the internet how to extract todays date into that format or create your own custom function to convert date in that format.
After that you need to compare
let firstPart = (todayDate === dateSplit[0])?'today':dateSplit[0];
So second part contains time, you can always refer the moment library to change the date and time formats according to how you need. So that wont be a problem. Hence your main logic is implemented in the above steps i mentioned.
let finalString = `${firstPart} , ${secondPart}`
this final string will be displayed under the chats. And here the second part variable is nothing but the time whihc is extracted according to your format by the moment.js after you pass the dateSplit1 whihc contains the time, Hope you are clear, otherwise ask me for doubts.
Update answer :
displayDate(messagedateTime) {
let time = messagedateTime;
let arr = time.split("T");
let date = new Date().getDate()
let month = new Date().getMonth() +1
let year = new Date().getFullYear()
let todayDate = `${year}-${month}-${date}`
let firstPart = (todayDate === arr[0])?'today':arr[0];
let secondPart = (arr[1].split("."))[0]
let finalString = `${firstPart} ${secondPart}`
return finalString
console.log(finalString,'wowow')
}
You can also try the js fiddle link Check here to play around
Just to show you how to use it. make it string to make it in your own format then if moment library or any other library don't have that custom format you want.
let datetime = "2019-11-13T03:07:58.359";
var d = datetime.split("T");
console.log(d);
let timeday = moment(d[0]).calendar();
timeday=timeday.toString();
timeday=timeday.replace(" at","");
console.log(timeday.toString());
I'm doing a SQL query in Node-Red to output a load of time/value data. This data is then passed to a web page for display in a graph.
Previously I've used php to do the SQL query, which I'm trying to replace. However SQL queries in php are delivered in a different format.
With Node-Red, I get:
[
{
"Watts": 1018,
"Time": 1453825454
},
{
"Watts": 1018,
"Time": 1453825448
},
{
"Watts": 1010,
"Time": 1453825442
}]
With PHP, I get:
[
[1453819620000,962],
[1453819614000,950],
[1453819608000,967],
[1453819602000,947]
]
I think I'm getting an array from php and an array of JSON objects from Node-Red. How do I convert the Node-Red object to be output from Node-Red in the same format as the PHP is? (Ie: I want to handle the processing at the server, rather than the client.)
A function node can be used to generate something in the same format.
var array = msg.payload;
var phpFormat = "[";
for (var i=0; i<array.length; i++) {
phpFormat += "[" +
// time format differ, NodeJS is in seconds
// php is in milliseconds
(array[i].Time * 1000 ) +
"," +
array[i].Watts + "],";
}
//take the last "," off
phpFormat = phpFormat.substring(0,phpFormat.lenght - 1);
phpFormat += "]";
msg.payload = phpFormat;
return msg;
I've had a bit of help from a chap at work and here is what he's come up with, modified for node-red by me:
var outputArray = [];
for(var i in msg.payload){
var entryData = [msg.payload[i]['Time']];
for(var attr in msg.payload[i]) {
if(attr!='Time') {
entryData.push(msg.payload[i][attr])}
};
outputArray.push(entryData); }
var returnMsg={"payload":outputArray};
return returnMsg;
I know, I know, this question is over 2 years old... however, for the next 500 people seeking an answer to a similar problem, I'd like to highlight the new JSONata expression feature built-in to the change node. Using this simple expression:
payload.[Time, Watts]
transforms your JS objects into the requested output of an array of arrays. In fact, much of my old repetitive looping through arrays has been replaced with some simpler (to me) expressions like this.
The magic of the lambda syntax evaluator is documented on the JSONata site. There you will also find the online exerciser where you can build an expression against your own data and immediately see the resulting structure.
Note: in order to use a jsonata expression in your change node, be sure to select the J: pulldown next to the input field (not the {} JSON option)... two totally different things!
Im trying to work out how to append a zero to a specific JSON decoded array value for multiple records stored in a MySQL table according to some conditions.
for example, for table 'menu', column 'params'(text) have records containing JSON decoded arrays of this format:
{"categories":["190"],"singleCatOrdering":"","menu-anchor_title":""}
and column 'id' has a numeric value of 90.
my goal is to add a zero to 'categories' value in menu.params whenever (for example) menu.id is under 100.
for this records the result being
{"categories":["1900"],"singleCatOrdering":"","menu-anchor_title":""}
so im looking for a SQL Query that will search and find the occurrences of "categories": ["999"] in the Database and update the record by adding a zero to the end of the value.
this answer is partially helpful by offering to use mysql-udf-regexp but its referring to REPLACE a value and not UPDATE it.
perhaps the REGEXP_REPLACE? function will do the trick. i have never used this library and am not familiar with it, perhaps there is an easier way to achieve what i need ?
Thanks
If I understand your question correctly, you want code that does something like this:
var data = {
"menu": {
"id": 90,
"params": {
"categories": ["190"],
"singleCatOrdering": "",
"menu-anchor_title": ""
}
}
};
var keys = Object.keys(data);
var columns;
for (var ii = 0, key; key = keys[ii]; ii++) {
value = data[key];
if (value.id < 100) {
value.params.categories[0] += "0";
alert(value.params.categories[0]);
}
}
jsFiddle
However, I am not using a regular expression at all. Perhaps if you reword the question, the necessity of a regex will become clearer.
I use jqGrid and my grid definition is like that:
...
colNames:['Type','Date','Message','User Name','Host'],
colModel:[{name:'type',index:'type', width:100},
{name:'date',index:'date', sorttype:'date', formatter:'date',
formatoptions: {newformat:'d-M-Y'}, width:100},
{name:'log',index:'log', width:200},
{name:'username',index:'username', width:50},
{name:'host',index:'host', width:50}],
...
When I debug my coming data one of the date value (it is Number) is as follows:
1322550786997
Grid shows it like that:
29-Nov-2011
Everything is OK till this point. However when I want to sort my date column it doesn't change anything.
Any ideas?
The problem is that decoding of the Unix (formatoptions: {srcformat: 'U', newformat: 'd-M-Y'}) date 1322550786997 get us 19-Dec-43879 and not 29-Nov-2011. You correct representation of the date will be the string "\/Date(1322550786997)\/" instead of the number 1322550786997.
See the demo:
UPDATED: You can also use the following custom formatter as a workaround
formatter: function (cellval, opts) {
var date = new Date(cellval);
opts = $.extend({}, $.jgrid.formatter.date, opts);
return $.fmatter.util.DateFormat("", date, 'd-M-Y', opts);
}
It creates Date and then use original date formatter to convert it to the format 'd-M-Y'. See here the demo.