I am using react js. I have some json data where I am fetching the timestamp. It has date and time both. For example:
timestamp":"2020-03-23T14:00:00.000Z"
Now after fetching all the json data including timestamp. I wanna make a chart, but I only want to use the date in my chart, not the time. How do I only get the date from the timestamp in the form of 2020/03/23 not the- but with /? I am using chartjs for making the chart Thanks.
Edit:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempsymbolsDate.replace("-", "/"); //here it doesn't replace with `/`
console.log(tempsymbolsDate);
}
You can split the string using "2020-03-23T14:00:00.000Z".split("T")[0] to get the date without the time.
To replace - characters with /, use the str.replace(searchvalue, newvalue) method. For example:
"2020-03-23".replace(/-/g, "/")
Edit:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempsymbolsDate = tempsymbolsDate.replace(/-/g, "/");
console.log(tempsymbolsDate);
}
Edit 2:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempArray = tempsymbolsDate.split("-");
tempsymbolsDate = tempArray[2] + "/" + tempArray[1] + "/" + tempArray[0];
console.log(tempsymbolsDate);
}
Related
After saving DateTime in controller, I pass it back to the View but when it's displayed in view the value became /Date(1545062400000)/.
I already checked in the controller while in process if the data was changed but it did not since I'm just passing the viewmodel in the view.
[HttpPost]
public ActionResult UpdateHeader(RecordViewModel recordViewModel)
{
var ResultMessage = "";
if (ModelState.IsValid)
{
Record record = (from c in context.Records
where c.RecordId == recordViewModel.RecordId
select c).FirstOrDefault();
if (record == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
record.Description = recordViewModel.Description;
record.Date = recordViewModel.Date;
record.Remarks = recordViewModel.Remarks;
try
{
context.SaveChanges();
ResultMessage = "Record successfully updated.";
}
catch (Exception ex)
{
ModelState.AddModelError("", ErrorHelper.GetInnerException(ex));
ResultMessage = "Error: " + ErrorHelper.GetInnerException(ex);
}
}
var result = new { Model = recordViewModel, ResultMessage = ResultMessage };
return Json(result, JsonRequestBehavior.AllowGet);
}
Angular
self.submitEdit = function () {
var updateRecordHeader = RecordServices.updateRecordHeader(self.header)
.then(function successCallback(response) {
self.header = response.data.Model;
self.header.ResultMessage = response.data.ResultMessage;
}, function errorCallback(response) { toastr.error(response.statusText); });
}
The /Date(1545062400000)/ is known as date ticks using UNIX timestamp format since RFC7519 "epoch" (January 01, 1970), which cannot be directly consumed as JS Date object without converting it first. The reason behind usage of the ticks is JSON format doesn't have specific representation for DateTime struct when serialized to plain strings (see this reference).
You can create a custom function to convert ticks into JS Date object:
function toJSDate(value) {
var regex = /Date\(([^)]+)\)/;
var results = regex.exec(value);
var date = new Date(parseFloat(results[1])); // or parseInt
return date;
}
Or even simpler without regex by picking numeric values directly like this:
function toJSDate(value) {
var date = new Date(parseFloat(value.substring(6))); // or parseInt
return date;
}
Then use that function for ticks-to-date conversion:
// example
var header = response.data.Model;
var dateObject = toJSDate(header.Date);
// assign date object afterwards
Note that you may need to create another object structure which resembles response.data.Model but using server-side Date property with JS date object.
As an alternative you may create a getter-only string property which uses ToString() to convert DateTime value into desired string representation, then use it inside JS.
Side note:
Avoid using viewmodel property name which exactly matches built-in JS function names & objects (i.e. Date) for clarity.
Related issues:
How do I format a Microsoft JSON date?
Converting .NET DateTime to JSON
The Problem
Within an AJAX call, I am trying to retrieve a JSON object with an appended auto-generated identifier. Is it possible to use regex to select a JSON object that starts with a specific string?
E.g. below targeting announcements_414988813
jQuery
const parent = $('.c-banner');
let data;
$.getJSON('path_to_data.json', function (result) {
const data = result["jcr:content"]["parsys"];
const announcement = data["/^/announcements"];
let date = announcement.eventDate;
let _html = "";
_html += '<p>' + date + '</p>';
parent.append(_html);
});
JSON
{
"jcr:content": {
"parsys": {
"announcements_414988813": {
"eventDate": "Fri Jan 18 2019 00:00:00 GMT-1000",
"title": "Pizza Day!",
}
}
}
}
After you've extracted the data object, you should be able to loop through its keys and find the one that matches.
var announcement = {}
for (key in data) {
if (key.match(/^announcements/)) {
announcement = data[key];
}
}
Note that if your parsys object has multiple announcements, this would give you the last one. announcement will just remain an empty object if it doesn't find any. (Break out of the loop if you want the first one, or save them all in an array if you need them all.)
i have an array in my angular applicaton for eg:
searchTerm : any[]
I have a textbox with a value {'state':'tn'} and want to push this to the searchTerm array. Currently i add this item to a service and then array as:
private onItemAdded(event): void {
const filter = JSON.parse('"' + event['value'] + '"');
this.dataService.addFilter(filter);
}
But it is storing as "{'state':'tn'}"
How can i parse this without double quotes in the front?
console.log('ADDED FILTER', event['value']);
here the value is printed as {'state':'value'}
but when assign to variable as below, it adds double quotes
let filter = event['value'];
Thanks
why you are using parse?, it is for converting from JSON to object, instead use stringify which will parse your object to JSON(string)
const obj = "{'state':'tn'}";
let filter = JSON.stringify(obj);
filter = filter.slice(1, filter.length - 1);
console.log(filter);
i have a JSON like this:
{"name1":123,"name2":123,"name3":123}
i want put "" in numbers To stay like this:
{"name1":"123","name2":"123","name3":"123"}
Anybody know a nodejs code to do this?
Assuming the object is already parsed and stored in a variable somewhere, you can do:
Object.keys(myObject).reduce((o, k) => Object.assign(o, {
[k]: myObject[k].toString()
}), {})
As Judson Terrel was saying above, you should consider using JSON.stringify(myJsonObject)
but if you so desired to use regex, here it is
let str = '{"name1":123,"name2":123,"name3":123}';
let result = str.replace(/\b(\d+)/g, "\"$1\"");
console.log (result);
//console-output => {"name1":"123","name2":"123","name3":"123"}
The simplest way is to parse the JSON string to an object using JSON.parse, and then convert the object values to string with the String function, like this:
var strg = '{"name1":123,"name2":123,"name3":123}';
var obj = JSON.parse(strg);
for (var i in obj){
obj[i] = String(obj[i])
}
console.log(obj)
I am trying to dynamicalyl populate my jqGrid...
I have been running into a hell of a time getting my jquery grid to populate with data. How would you set up your jquery string? I create an object like so...
public static object JsonHelper(TemplateModel model){
var values = model.Template;
var JsonDataList = new {
total = 1,
page = 1,
records = model.Template.Count,
rows = (from val in values
select new {
cell = //new string(
":[\"id\" :\"" + val.EncounterId +",\""+
"\""+val.MRN + ",\""+
"\""+val.HostpitalFinNumber +",\""+
"\""+val.FirstName+",\"" +
"\""+val.LastName +",\"" +
"\""+val.DateOfBirth.ToString() +",\""+
"\""+val.CompletedPathway +",\""+
"\""+val.CompletedPathwayReason +",\""+
"\""+val.PCPAppointmentDateTime.ToString() + ",\""+
"\""+ val.SpecialistAppointmentDateTime.ToString() + ",\""+
"\""+val.AdminDate.ToString()+"\"]"
}).ToString()//.ToArray()
};
return JsonDataList;
}
That is just an object,
However I return the object using the Json methbod call...
Here is what I do...
return Json(DataRepository.JsonHelper(model.FirstOrDefault()), JsonRequestBehavior.AllowGet);
I get the model from the search call... I have know idea what I am doing wrong... Can somebody give me a simple example of how to turn a simple object into json?
I suggest you look into Google's gson library. I used it when working with JSON and it worked perfectly.
Well, I just used a string builder and a good JSON debugger to get the right strings, and it appears as though it works...