0

I am getting data from Json which also contains date. Now the date is displayed in Numerics. I were able to convert Date into a readable format but that's not my requirement. I want the date to be displayed in mm/dd/yy format.

$.ajax({
        url: '@Url.Action("ReqVacancy", "AdvertisementMaintenance")',
        type: 'GET',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { "RequisitionID": id },
        success: function (data) {
              var result1 = "";
                divid.html('');
$.each(data, function (id, result) {
                    if (result != 0) {
                        var result1 = "<tr>"
                        + '<td><input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '></td>'

                                            + "<td>" + result.VacancyId + "</td>"
                                            + "<td>" + result.PositionId + "</td>"
                                            + "<td>" + result.Reason + "</td>"
                                            + "<td>" + eval('new' + result.StartDate.replace(/\//g, ' ')) + "</td>"
                                            + "<td>" + eval('new' + result.EndDate.replace(/\//g, ' ')) + "</td>"
                                               + "<tr>"
                        $('#tbody').append(result1);
                    }


                });
      });

And the result goes here....

    VacancyId   Position    Reason         StartDate                                                EndDate
    1           Fresher      Not Avail     Sat Mar 07 2015 00:00:00 GMT+0530 (India Standard Time)  Tue Mar 17 2015 00:00:00 GMT+0530 (India Standard Time)

My requirement is:

VacancyId   Position         Reason        StartDate          EndDate
    1           Fresher      Not Avail      03/07/2015        03/17/2015

I could do the above taking a variable and then using getMonth(), getDate() and getFullYear(). But the code goes long and I have been asked to do it within a single line of code. Any help is highly appreciated. Thanks.

Zaker
  • 537
  • 16
  • 30

4 Answers4

2

There's nothing to do with json for your date format, you can do something like this in javascript.

var startDate = new Date(result.StartDate);
var formattedStartDate = startDate.getMonth() + "/" + startDate.getDate() + "/" + startDate.GetYear();

Your overall code should look like this.

 $.each(data, function (id, result) {
        if (result != 0) {
            var startDate = eval('new' + result.StartDate.replace(/\//g, ' '));
            var formattedStartDate = startDate.getMonth() + "/" + startDate.getDate() + "/" + startDate.GetYear();
            var endDate = eval('new' + result.EndDate.replace(/\//g, ' '));
            var formattedEndDate = endDate.getMonth() + "/" + endDate.getDate() + "/" + endDate.GetYear();
            var result1 = "<tr>"
            + '<td><input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '></td>'

                                + "<td>" + result.VacancyId + "</td>"
                                + "<td>" + result.PositionId + "</td>"
                                + "<td>" + result.Reason + "</td>"
                                + "<td>" + formattedStartDate + "</td>"
                                + "<td>" + formattedEndDate + "</td>"
                                   + "<tr>"
            $('#tbody').append(result1);
        }

Solution: 2

Create a prototype for date as :

Date.prototype.toMMDDYYYY = function(){
  return this.getMonth() + "/" + this.getDate() + "/" + this.getFullYear()
};

Use Case:

new Date().toMMDDYYYY();

In your screen:

$.each(data, function (id, result) {
            if (result != 0) {
               var result1 = "<tr>"
                + '<td><input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '></td>'

                                    + "<td>" + result.VacancyId + "</td>"
                                    + "<td>" + result.PositionId + "</td>"
                                    + "<td>" + result.Reason + "</td>"
                                    + "<td>" + new Date(result.StartDate.replace(/\//g, ' ')).toMMDDYYYY()+ "</td>"
                                    + "<td>" + new Date(result.EndDate.replace(/\//g, ' ')).toMMDDYYYY()+ "</td>"
                                    + "<tr>"
                $('#tbody').append(result1);
            }

Update: with live example

//Somewhere globally...
Date.prototype.toMMDDYYYY = function(){
  return this.getMonth() + "/" + this.getDate() + "/" + this.getFullYear()
};

//expecing your date string looks like this

var startDate = new Date("Sat Mar 07 2015 00:00:00 GMT+0530 (India Standard Time)");
var data = [{"PositionId":1,"Reason":"Fresher","StartDate":"/Date(1425666600000)/","EndDate‌":"/Date(1426530600000)/","VacancyId":1}];
$.each(data, function (id, result) {
            if (result != 0) {
              //Your rest of the code
             alert( eval("new " + result.StartDate.replace(/\//g, ' ')).toMMDDYYYY());
            }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mox Shah
  • 2,967
  • 2
  • 26
  • 42
  • Thanks for your reply. Will check for that – Zaker Mar 17 '15 at 09:19
  • You just updated your question, anyways if you want to do it in single line of code, than you can create your own extensions, that returns specific format, even you can use it globally later. – Mox Shah Mar 17 '15 at 09:22
  • 2
    I think you need to change your code a bit.OP wants in mm/dd/yy format – SpringLearner Mar 17 '15 at 09:23
  • @User, I've updated my answer with another solution, You may need to verify, let me know if it doesn't help. – Mox Shah Mar 17 '15 at 09:35
  • What do you mean by no result? are you getting any error? it would be better you post exact string you're getting in `result.StartDate`. – Mox Shah Mar 17 '15 at 09:54
  • @MokshShah I get the error as Uncaught TypeError: undefined is not a function --within Console for the first Sol. – Zaker Mar 17 '15 at 09:59
  • @User, make sure you're parsing your `result.StartDate` correctly as `eval('new' + result.StartDate.replace(/\//g, ' '));` – Mox Shah Mar 17 '15 at 10:01
  • @MokshShah Thanks for your snippet and that keeps working but why it doesn't works for me if I place the code within my page. I can find that the method keeps calling if I place the debugger within prototype and I get the result to be as NaN/NaN/NaN – Zaker Mar 17 '15 at 10:28
  • @User, got your issue, its with your JSON, give 5 mins will update my ans with your JSON. – Mox Shah Mar 17 '15 at 10:36
  • @MokshShah Thanks I got it from you and Guruprasad Rao's answers. Marked as useful. – Zaker Mar 17 '15 at 12:04
  • @User You may mark it as answer, if its exactly what you're looking for. – Mox Shah Mar 17 '15 at 12:32
  • 1
    @Moksh Shan it say's that I cannot accept answer for the rest two days. And thanks without u and Guruprasad Rao it would not have been possible. – Zaker Mar 17 '15 at 12:45
1

You can do like this

$.each(data, function (id, result) {
                    if (result != 0) {
                       var stDate=new Date(result.StartDate);
                       var endDate=new Date(result.EndDate);
                        var result1 = "<tr>"
                        + '<td><input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '></td>'
                                            + "<td>" + result.VacancyId + "</td>"
                                            + "<td>" + result.PositionId + "</td>"
                                            + "<td>" + result.Reason + "</td>"
                                            + "<td>" + stDate.getMonth()+1 +"/" + stDate.getDate() + "/" + stDate.getFullYear()  + "</td>"
                                            + "<td>" + endDate.getMonth()+1 +"/" + endDate.getDate() + "/" + endDate.getFullYear()  + "</td>"
                                               + "<tr>"
                        $('#tbody').append(result1);
                    }


                });
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • I get the result as NaN1/NaN/NaN – Zaker Mar 17 '15 at 09:33
  • Open browser console. Place a debugger at result1. once it reaches there your stDate and endDate will have values. just execute that stDate.getMonth and see what you are getting..?? – Guruprasad J Rao Mar 17 '15 at 09:38
  • @GuruprasadRao you need to convert it to date object before putting it into `new Date()`. – Mox Shah Mar 17 '15 at 09:42
  • @MokshShah. As of my knowledge, `new Date()` takes string too as parameter and then it will convert it into date object. Correct me if am wrong. – Guruprasad J Rao Mar 17 '15 at 09:50
  • @GuruprasadRao I get the error as __proto__: Invalid Date – Zaker Mar 17 '15 at 09:54
  • @User.. Just try stringyfying data before you pass it to each loop like -> `data=JSON.stringify(data)` and let me know what you see?? **EDIT** : Even try doing this `data=$.parseJSON(JSON.stringify(data));` – Guruprasad J Rao Mar 17 '15 at 09:54
  • 1
    Yes of course it takes string parameter too, but I feel it should be parsed, before you put into `Date()` – Mox Shah Mar 17 '15 at 09:55
  • 1
    I agree.. Just added it in comments. Lets c if @User tries it gets what he desires then will add it in answer.. – Guruprasad J Rao Mar 17 '15 at 09:56
  • @GuruprasadRao you mean to place the code just before each loop. Is it like data=JSON.stringify(data);$.each(data, function (id, result) {........ Is it the way you specified. Please correct me if I am wrong. Thanks – Zaker Mar 17 '15 at 10:10
  • @GuruprasadRao Thanks for being so kind but no result. This time I don't get any error but I get the result as :NaN1/NaN/NaN – Zaker Mar 17 '15 at 10:16
  • @GuruprasadRao the above for second line and for the first one I get the error as Uncaught TypeError: Cannot use 'in' operator to search for '120' in [{"PositionId":1,"Reason":"Fresher","StartDate":"/Date(1425666600000)/","EndDate":"/Date(1426530600000)/","VacancyId":1}] – Zaker Mar 17 '15 at 10:18
  • @GuruprasadRao any suggestions please. – Zaker Mar 17 '15 at 10:29
  • @User just put `console.log(result.StartDate)` and verify what type of string are you getting in JSON ? – Mox Shah Mar 17 '15 at 10:30
  • @GuruprasadRao here it is /Date(1425666600000)/ – Zaker Mar 17 '15 at 10:35
  • I think its giving back as unixTimestamp value. So Just try doing as below and let me know the result. `var stDate=new Date(result.StartDate*1000)`. Let me know the value you are getting now in stDate – Guruprasad J Rao Mar 17 '15 at 10:58
  • @GuruprasadRao Now it is showing as Invalid Date within console for stDate. – Zaker Mar 17 '15 at 11:17
  • Ok @User.. Jus go through **[Link](http://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript)**.. You will find useful methods to get rid of this.. – Guruprasad J Rao Mar 17 '15 at 11:21
  • 1
    Marked as useful for your effort . Thanks I got it from your's and @Moksh Shah's effort. – Zaker Mar 17 '15 at 12:04
  • 1
    Cool @User. If you have solved it then post the answer and mark it as answer so that it will be helpful for others. Happy Coding.. – Guruprasad J Rao Mar 17 '15 at 12:29
  • It say's that I cannot accept answer for the rest two days. And thanks without u and @Moksh Shah it would not have been possible. – Zaker Mar 17 '15 at 13:37
  • 1
    @User.. Yea that's the SO rule. No issues accept it after 2 days.. :) – Guruprasad J Rao Mar 17 '15 at 13:41
1

I just got the answer from @Moksh Shah & also @Guruprasad Rao. Thanks for your help. It look like this here..

$.each(data, function (id, result) {
                  console.log(result.StartDate);
                    if (result != 0) {
//I just had to use new Date(......) here
                        var endDate = new Date(eval('new' + result.EndDate.replace(/\//g, ' ')));
                        var formattedEDate = endDate.getMonth() + 1 + '/' + endDate.getDate() + '/' + endDate.getFullYear();
                        var SDate = new Date(eval('new' + result.StartDate.replace(/\//g, ' ')));
                        var formattedSDate = SDate.getMonth() + 1 + '/' + SDate.getDate() + '/' + SDate.getFullYear();
                        //console.log(endDate);
                        var result1 = "<tr>"
                        + '<td><input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '></td>'

                                            + "<td>" + result.VacancyId + "</td>"
                                            + "<td>" + result.PositionId + "</td>"
                                            + "<td>" + result.Reason + "</td>"
                                            + "<td>" + formattedSDate + "</td>"
                                          + "<td>" + formattedEDate + "</td>"
                                               + "<tr>"
                        $('#tbody').append(result1);
                    }
Zaker
  • 537
  • 16
  • 30
0

It can be a possible duplicate of this

Your code should look like:

      if (result != 0) {
                    var result1 = "<tr>"
                    + '<td><input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '></td>'

                                        + "<td>" + result.VacancyId + "</td>"
                                        + "<td>" + result.PositionId + "</td>"
                                        + "<td>" + result.Reason + "</td>"
                                        + "<td>" + dateFormat(result.StartDate) + "</td>"
                                        + "<td>" + dateFormat(result.EndDate) + "</td>"
                                           + "<tr>"
                    $('#tbody').append(result1);
                }


    function dateFormat(dateObject) {
          var d = new Date(dateObject);
          var day = d.getDate();
          var month = d.getMonth();
          var year = d.getFullYear();
          if (day < 10) {
           day = "0" + day;
          }
          if (month < 10) {
            month = "0" + month;
          }
          year = year.toString().slice(2);
          var date = day + "/" + month + "/" + year;

          return date;
      }
Community
  • 1
  • 1
Jangya satapathy
  • 866
  • 8
  • 20