Parsing and formatting JSON date variable - json

I am parsing a JSON object with JavaScript and displaying it in a styled HTML table.
The date variable comes as a long string. (e.g. 2011-11-23 10:21:49.695805)
How can I format the date so as to be displayed: year-month-day, hour-minute instead of 2011-11-23 10:21?
The AJAX call:
$$.ajax({
url: '/ajax/myfolder',
dataType:"json",
success: function(json) {
$$('#JsonGrid').append(CreateTableView(json, "jsonFeed", true)).fadeIn();
parseDate();
}
});
function parseDate() {
}
The json object:
[{"status": "success", "date": "2011-11-23 10:21:49.695805", "user": "xy", "jobname": "jobnamexyz"}]

You can use date functions, DateJS, etc., but if the format is fixed as in your example you can just take the first sixteen characters:
var date = json["date"].substr(0,16);
EDIT: sorry, just noticed you wanted a comma in there. So:
var date = json["date"].substr(0,10) + ", " + json["date"].substr(11,5);
EDIT 2: OK, try moving the call to parseDate() to before you call CreateTableView(), so you can "fix" the data before it is used. The following assumes the json is an array of objects:
success: function(json) {
parseDate(json);
$$('#JsonGrid').append(CreateTableView(json, "jsonFeed", true)).fadeIn();
function parseDate(data) {
for (var i=0; i<data.length; i++)
if (data[i]["date"])
data[i]["date"] = data[i]["date"].substr(0,10)
+ ", " + data[i]["date"].substr(11,5);
}

You can use String.match method to parse the parts of string like "2011-11-23 10:21:49.695805". For example the code
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"([T| ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var dateString = "2011-11-23 10:21:49.695805";
var d = dateString.match(new RegExp(regexp));
will initialize d as array where d[1], d[3], d[5], d[7], d[8] and d[10] are year (2011), month (11), day (23), hour (10), minutes (21), seconds (49). The d[12] will be 695805 and only the first tree digits of it are milliseconds. So you can either create a Date like
var date = new Date(d[1],d[3],d[5],d[7],d[8],d[10],d[12].substr(0,3));
or display the parsed date as another string in any other format which you prefer.

$$.ajax({
url: '/ajax/myfolder',
dataType:"json",
success: function(json) {
$$('#JsonGrid').append(CreateTableView(json, "jsonFeed", true)).fadeIn();
parseDate(json);
}
});
function parseDate(json) {
var arr = json["date"].split(/:/);
var date = arr[0] + ":"+arr[1];
alert(date);
return date;
}

Maybe this jQuery extension can help you out: http://momentjs.com/
Like:
var now = moment();
var formatted = now.format('dddd, MMMM Do YYYY');

Related

Parse random String & return Value (JSON)

Edit: It works pretty well now and this makes it possible to reference URLs in a JSON file and return their related pairs (e.g game name / year / image url). Here's the code.
AFRAME.registerComponent('jfetch', {
schema: {},
init: function () {
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsongames = JSON.parse( event.target.response )
var keys = Object.keys(jsongames);
var random = jsongames[keys.length * Math.random() << 0];
var games = random.Title + ' (' + random.Developer + ')'
var textEntity = document.querySelector('#text');
textEntity.setAttribute("value", games)
var gurl = random.Imageurl
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:gurl});
} );
request.send( null );
}
});
Thanks for the help everyone!
Original Question: I would like to fetch a random "Title" string in my Json file and return its corresponding value. I know the simple test code works but I have no idea how to apply it to an array with lots of objects and to add the random parsing element. Can someone please help me with a solution? This is my remix file.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonGames = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonGames.Title)
} );
request.send( null );
}
});
You can not manipulate JSON file as you would with an object, because JSON is a string. Thats why we parse them (converting into Javascript object).
From your question I assume that you want to get a random value of key-value pairs, where key is a Title. In that case, first you parse JSON response (as you do already - var jsonGames = JSON.parse( event.target.response )). So now you have your Javascript object to work with - jsonGames and all what is left is to get that random key of it. To do that you can, for ex:
var jsonGames = JSON.parse( event.target.response )
var keys = Object.keys(jsonGames);
var random = jsonGames[keys[keys.length * Math.random() << 0]];
textEntity.setAttribute("value", random.Title)
Please comment if something is not right.

How can I order my string in as3

A complex question :
I've got this code (not the complete code, but the essentials for the question, I think) :
var $pmm:String;
var $pms:String;
var $bmm:String;
var $bms:String;
function get haute1():String { return $pmm; };
function get haute2():String { return $pms; }
function get basse1():String { return $bmm; };
function get basse2():String { return $bms; };
accueil.todayHaute_txt.htmlText = haute1;
accueil.todayBasse_txt.htmlText = basse1;
accueil.todayHauteSecond_txt.htmlText = haute2;
accueil.todayBasseSecond_txt.htmlText = basse2;
"haute1" is an hour (in 24h format). Something like "13h25".
It changes everyday.
Question : How can put them in ascending order in AS3 ?
Example : If haute1 = 15h20, haute2= 6h00, basse1= 11h and basse2 = 17h, the function would put them in this order :
"haute2", then "basse1", then "haute1" and finally "basse2".
Thx
EDIT
I add this code that I have. is it helping you ?
/ Assigns hours and tidal heights
$pmm = convdateheure($tpbs[1 + $deltapm]);
$pms = convdateheure($tpbs[3 + $deltapm]);
$bmm = convdateheure($tpbs[2 - $deltapm]);
$bms = convdateheure($tpbs[4 - $deltapm]);
function convdateheure($valeur:Number):String
{
var $heure:Number = Math.floor($valeur);
var $minute:Number = Math.floor(Math.floor(($valeur - Math.floor($valeur)) * 100) * 0.6);
var hoursLabel:String = "", minsLabel:String = "";
if ($heure == 24) $heure = 0; // Check if at the 24 hour mark, change to 0
if ($heure < 10) hoursLabel += "0" + $heure.toString(); else hoursLabel = $heure.toString();
if ($minute < 10) minsLabel += "0" + $minute.toString(); else minsLabel = $minute.toString();
return hoursLabel + ":" + minsLabel;
}
If you want to order some dates written in some String format:
One way would be, depending on you date string format, just to push them into array and sort them as strings, then read them all.
Another way would be to first parse those strings into Date instances, and push their Date.time property to array, sort it, then do reverse: parse all time values from sorted array into new Date instances then use Date.toString or similar.
Assuming that $valuer is a numerical value:
var timesArray:Array = new Array();
var convertedTimesArray:Array = new Array();
function sortTimes():void{
timesArray.push($valuer);
timesArray.sort(Array.NUMERIC);
}
function convertTimes():void{
convertedTimesArray = []; // clear the array
for (var i:int = 0; i < timesArray.length; i++){
var s:String = convdateheure(timesArray[i]);
convertedTimesArray.push(s);
}
}
That should give you one array of actual times, sorted in numerical order, and one array sorted in the same numerical order, but converted to String values using your function.

Parse Json object

I have a following Json object:
data = [{"$id":"1","ID":2,"Name":"Exceptional trip to ZG"}]
I need to parse it so I can display individual attributes on my webpage.
I tried using this code:
var lang = '';
var obj = $.parseJSON(data);
$.each(obj, function() {
lang += this['ID'] + "<br/>";
});
$("#mybox1").html(lang);
but it doesn't work as $.parseJSON expects Json string like this one:
[{"$id":"1","ID":2,"Name":"Exceptional trip to ZG"}] - same only with quotation marks around it. This code works perfectly with Json string.
Why are you trying to parse? It's already a valid object. Check this fiddle.
This will accomplish your task:
var data = [{
"$id": "1",
"ID": 2,
"Name": "Exceptional trip to ZG"
}];
var lang = '';
$.each(data, function () {
lang += this['ID'] + "<br/>";
});
$("#mybox1").val(lang);

Knockout.js format date item

In my view I wish to display a knockout.js binded field that contains a date. It is just a display field and not an input field. Something like below when basemodel.actionDate = ko.observable()
<p class="display-field" data-bind="text: baseModel.actionDate"/>
However this is displayed as follows:
2013-06-17T11:56:18.4537687Z
What is the easiest way to format this dd mm yyyy. eg: 17 June 2013?
I recommend the moment.js date formatting library.
Using it, you can do something like this in your view:
<p class="display-field" data-bind="text: moment(baseModel.actionDate()).format('LL')"/>
Either make sure the service output it in a correct format, or format in client side
If you want todo it client side then you can parse the ISO date string into a Date object and then use jQuery globalize to format it to desired format.
I use KO extenders for this
http://jsfiddle.net/vRf5B/42/
ko.extenders.date = function(target, format) {
return ko.computed({
read: function() {
var value = target();
if(typeof value === "string") {
value = new Date(value);
}
format = typeof format === "string" ? format: undefined;
value = Globalize.format(value, format);
return value;
},
write: target
});
}
update
I got a question on my blog how to retrieve the raw date value
It can be done my exposing the raw value on the computed like
http://jsfiddle.net/vRf5B/91/
Declare format function:
Date.prototype.toFormattedDate = function () {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(mm + "/" + dd + "/" + yyyy);
};
And use it with the date strings as:
<span data-bind="text: new Date(TaxAuthority.RegDate).toFormattedDate()"></span>
I had some issues (I think) with the mapping plugin trying to use the extender. Since I'm only displaying dates and not allowing them to be edited I prefer to just use a binding handler like this:
Shipped on <span data-bind="date: shipDt"></span>
Here's the handler:
ko.bindingHandlers.date =
{
update: function (element, valueAccessor: () => any, allBindingsAccessor: any)
{
return ko.bindingHandlers.text.update(element, function ()
{
var value: any = ko.utils.unwrapObservable(valueAccessor());
if (value == null)
{
return null;
}
if (typeof value === "string")
{
value = new Date(value);
}
return value.toShortDateString();
}, allBindingsAccessor, null, null);
}
};
I chose to add a prototype to Date object like this (and call toShortDateString on the Date object created in the handler)- but you can replace the logic above with Globalize or whatever you prefer.
Date.prototype.toShortDateString = function ()
{
return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
};
If you are referencing moment.js then I would actually format in the knockout model.
var BiographicViewModel = function (person) {
this.FirstName = ko.observable(person.first_name);
this.LastName = ko.observable(person.last_name);
this.DOB = ko.observable(moment(person.birth_date).format("MM/DD/YYYY"));
this.Gender = ko.observable(person.gender);
this.Country = ko.observable(person.country);
this.City = ko.observable(person.city);
};

How do I format this date string so that google scripts recognizes it?

I'm getting a json feed with a date string formatted like the following:
//2012-08-03T23:00:26-05:00
I had thought I could just pass this into a new Date as such
var dt = new Date("2012-08-03T23:00:26-05:00");
This works on jsfiddle but not in google scripts. It's returning an invalid date. After reading this post I recognize it may be how GAS interprets the date string so now I'm not sure how to reformat the date to make it work.
Is there a best way to reformat that date string so GAS can recognize it as a date?
Google Apps Script uses a particular version of JavaScript (ECMA-262 3rd Edition) and as you have discovered can't parse date/times in ISO 8601 format. Below is a modified function I use in a number of my Apps Scripts
var dt = new Date(getDateFromIso("2012-08-03T23:00:26-05:00"));
// http://delete.me.uk/2005/03/iso8601.html
function getDateFromIso(string) {
try{
var aDate = new Date();
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
return aDate.setTime(Number(time));
} catch(e){
return;
}
}
Found this other possible and very simple code that seems to also do the job :
function test(){
Logger.log(isoToDate("2013-06-15T14:25:58Z"));
Logger.log(isoToDate("2012-08-03T23:00:26-05:00"));
Logger.log(isoToDate("2012-08-03T23:00:26+05:00"));
}
function isoToDate(dateStr){// argument = date string iso format
var str = dateStr.replace(/-/,'/').replace(/-/,'/').replace(/T/,' ').replace(/\+/,' \+').replace(/Z/,' +00');
return new Date(str);
}
The hard and sure shot way to make it work if the format is known beforehand is to parse it.
var dtString = "2012-08-03T23:00:26-05:00";
var date = dtString.split('T')[0];
var time = dtString.split('T')[1].split('-')[0];
var tz = dtString.split('T')[1].split('-')[1];
var dt = new Date(date.split('-')[0] , date.split('-')[1] - 1, // month is special
date.split('-')[2], time.split(':')[0],
time.split(':')[1], time.split(':')[2] , 0);
I haven't tested this exact piece of code, but have used similar code. So, this gives you a fair idea of how to proceed.
This worked for me, when converting date-string to date-object in Google Script.
The date-string was taken from the Google Sheet cell by getValues() method.
From: 01.01.2017 22:43:34 to: 2017/01/01 22:43:34 did the job. And then the new Date().
var dateTimeObj = new Date(stringDate.replace(/^(\d{1,2})[-.](\d{1,2})[-.](\d{4})/g,"$3/$2/$1"));
As of now new Date() seems to work:
var dT = new Date("2012-08-03T23:00:26-05:00");
console.info("dT: %s or %d", dT, dT.getTime());
returns dT: Sat Aug 04 06:00:26 GMT+02:00 2012 or 1.344052826E12 in Google Apps Script