Lorenzo
Lorenzo

Reputation: 29427

Formatting a JSON Date with javascript

I am returning a JSON object from my web service method. The object has some dates in it and so the generated JSON is like the following:

{"d": [
    {"PeriodID":8,"Period":"072011","BeginDate":"\/Date(1294268400000)\/"},
    {"PeriodID":2,"Period":"052011","BeginDate":"\/Date(1293836400000)\/"}
]}

I am trying to convert this data in a string to be added as <option> elements in an HTML select. This is my code:

var rtypes = data.d;
$.each(rtypes, function (key, value) {
    var text = value.Period + " - " + "from " + eval(value.BeginDate.slice(1, -1));
    var option = $("<option></option>").attr("value", value.PeriodID).text(text);
    $('#rpCombo').append(option);
});

Now the questions:

  1. Can I format the date contained in the Period field (e.g. 072011) as a "July 2011"?
  2. How can I convert the result of eval(value.BeginDate.slice(1, -1)) that is for instance something like "Wed July 14......" into something like "14/07/2011"?

Thanks for helping

Upvotes: 0

Views: 1255

Answers (2)

mplungjan
mplungjan

Reputation: 177885

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse

For example

// create 1 of June 2011 from Jun 2011
var period = new Date(Date.parse("1 "+period)); 

Here is what I think you want

<script>

var months = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
var result = {"d": [
    {"PeriodID":8,"Period":"072011","BeginDate":1294268400000},
    {"PeriodID":2,"Period":"052011","BeginDate":1293836400000}
]}


var aPeriod, period, periodMM, periodYYYY, periodText, beginDate, beginMM, beginDD;
for (var i=0,n=result.d.length;i<n;i++) {
  aPeriod = result.d[i];

//  period = new Date(aPeriod.Period.slice(2),aPeriod.Period.slice(0,2)-1,1,0,0,0);
//  periodText = months[period.getMonth()]+" "+period.getFullYear();
  periodMM = parseInt(aPeriod.Period.slice(0,2),10);
  periodYYYY = aPeriod.Period.slice(2);
  periodText = months[periodMM]+" "+periodYYYY;
  beginDate = new Date(aPeriod.BeginDate);      
  beginDD = beginDate.getDate();
  if (beginDD<10) beginDD="0"+beginDD;
  beginMM = beginDate.getMonth()+1;
  if (beginMM<10) beginMM="0"+beginMM;
  periodText += " "+beginDD+"/"+beginMM+"/"+beginDate.getFullYear();
  alert(periodText)     
}

</script>

Upvotes: 1

Gats
Gats

Reputation: 3462

Not sure on the scale of your project, but I was doing a lot with dates recently and benefitted by implementing javascript extensions on the javascript Date object. This will make your life soooo much easier as it has for me and will take care of the above scenario and then some.

There is a very good article here: Javascript/Json Date Parsing

I did need to tweak it a little, but no looking back since implementing this approach.

Upvotes: 1

Related Questions