how to display an object by fetching using reactjs? - json

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());

Related

Swift: Firebase updateChildValues function Overwriting and Deleting Other Keys at Location

I am running into a peculiar issue when trying to simultaneously update values at different JSON branches in Firebase. The method provided in the documentation is perfect when it comes to creating new data,
let key = ref.child("posts").childByAutoId().key
let post = ["uid": userID,
"author": username,
"title": title,
"body": body]
let childUpdates = ["/posts/\(key)": post,
"/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)
but when I try to update data at multiple locations, it overwrites the other keys as if I was using setValue. Here is my code.
let userID = Auth.auth().currentUser?.uid
userRef = Database.database().reference()
let vehicle = ["make":make.text,
"model": model.text,
"year":year.text,
"color":color.text,
"doors":doors.text]
let driver = ["currentEvent":eventID]
let childUpdates = ["/users/\(userID!)": driver,
"/status/\(userID!)/driverInfo/vehicle": vehicle]
userRef.updateChildValues(childUpdates)
I have also attached a picture which shows which data is and isn't being deleted when the function is executed.
I believe what I am trying to do is possible, and from what I understand the whole purpose of updateChildValues is so that other children aren't overwritten.
Any help is appreciated. Thanks!
Currently you are updating the objects with objects like this:
let childUpdates = ["/users/\(userID!)": driver,
"/status/\(userID!)/driverInfo/vehicle": vehicle]
You are giving the object (a dictionary) as the value of the childUpdates dictionary. What this does is that replace all the children with this object meaning deleting the values for which you are sending nil for example in your case you have not included info or infoThat .
Now if you want to change only the values you want to give like only change the value of say make and model for vehicle and currentEvent for driver , you have to give the particular path for these values
["/users/\(userID!)/currentEvent": eventID,
"/status/\(userID!)/driverInfo/vehicle/make": make.text, "/status/\(userID!)/driverInfo/vehicle/model": model.text]
I think this will update the values of these locations as you expected.
HTH...
Correct me if I am mistaken, but if I understand what you're trying to do this might yield better results?
let userID = Auth.auth().currentUser?.uid
userRef = Database.database().reference()
let vehicle = ["make":make.text,
"model": model.text,
"year":year.text,
"color":color.text,
"doors":doors.text]
let driver = ["currentEvent":eventID]
let childUpdates = ["/users/": userID!),
"/status/\(userID!)/driverInfo": vehicle]
userRef.updateChildValues(childUpdates)

NodeJS: Adding new child nodes to JSON Object

lets say there is customer object, i need to add new element address to this json object customer. how can I achieve this?
Both of these are not altering the customer JSON object
customer['address'] = addressObj
customer.address = addressObj
and I can not use push() as this is not adding a new item in list of objects.
Thanks,
Naren
Maybe your addressObj is not properly formed.
This works for me:
var customer = {"name": "Naren"};
customer.address1 = "stackoverflow";
customer.address2 = {"fulladdress":"stackoverflow"};
JSON.stringify(customer)
Output:
"{"name":"Naren","address1":"stackoverflow","address2":{"fulladdress":"stackoverflow"}}"
Maybe I am not clear on what exactly you want to do but it sounds to me as if you want have a JSON and want to merge it with another JSON, creating just a JSON file.
let Json1 = {'Superman': 'Favorite' };
let Json2 = {'Supergirl': 'Greatest'};
let Json3 = {'IronFist': 'Top 10' };
You now want to add Supergirl (the new element) to Superman (the old element) I assume. Take a look here # merge-json a simple package which does its job well. You would code as follows:
use strict;
var mergeJSON = require("merge-json");
let Json1 = {'Superman': 'Favorite' };
let Json2 = {'Supergirl': 'Greatest'};
let Json3 = {'IronFist': 'Top 10' };
let Json6 = mergeJSON(Json1,Json2);
Json6=mergeJSON(Json6,Json3);
You would end up with as follows:
Json6 = {'Superman': 'Favorite', 'Supergirl': 'Greatest', 'IronFist': 'Top 10'}
This is how I make use of combining JSON information or text information into a JSON file. You can get much more sophisticated with the module mentioned above. (Just do not confuse merge-json with json-merge and other modules.)
If this is not what you are looking for my apologies, then I did not understand the question correctly.

How to format datatime for json

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.

jqGrid Doesn't Sort When Showing Epoch Time (since as milliseconds) as Date

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.

how to split a return text become individual string in extjs?

I want to split a returning text to become an individual string but i am noobie in extjs.Pls help me if any idea with it...thankz
my example code:
//my return "record" string is "1: 3-4-2011 to 9-4-2011"
Ext.getCmp('cboWeek').on('select', function(box, record, index)
{
DateFrom = new Date(record).format('m/d/Y');//split to 3-4-2011
DateTo = new Date(record).format('m/d/Y'); //split to 9-4-2011
Store.load({ params: {dateFrom : DateFrom, dateTo: DateTo }});
});
i think what you want is:
// if record is "1: 3-4-2011 to 9-4-2011"
var matches = record.match(/[0-9]+-[0-9]+-[0-9]+/g);
// matches[0] will be 3-4-2011 and matches[1] will be 9-4-2011
Store.load({ params: {dateFrom : matches[0], dateTo: matches[1] }});
</pre>
just a note: your dates are not what can be parsed using Date object neither using Ext.Date.parse, because month / day must be 2digits, if you manage to get 3-4-2011 to something like 03-04-2011 by doing "3-4-2011".replace(/([0-9]{1})[^0-9]+/g, '0$1-') you can get Date object using parse method of ext's date: Ext.Date.parse('03-04-2011', 'd-m-Y') then you can use format method on Date object