Reputation: 343
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"}]
Upvotes: 0
Views: 1575
Reputation: 4288
$$.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;
}
Upvotes: 0
Reputation: 150080
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);
}
Upvotes: 2
Reputation: 222007
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.
Upvotes: 0
Reputation: 9929
Maybe this jQuery extension can help you out: http://momentjs.com/
Like:
var now = moment();
var formatted = now.format('dddd, MMMM Do YYYY');
Upvotes: -1