0

Good Day Programmers how to convert the data inside to date time from for each loop of java script ajax.

Sample :

$.each(response, function (i, item) {
                        var tableData = "<tr><td><input type='checkbox' class='selectedCheckBox' data-value='" + item.trfbch + "'/></td><td>" + item.trfpon + "</td><td>" + item.dptnam + "</td><td>" + item.trfbch + "</td><td><button type='button' class='btn btn-primary deleteTrfBtn' data-value='" + item.trfbch + "'>Delete</button></td><td>" + item.trfsdt + "</td>";

                        $(".tablebodyinfo").append(tableData);
                    });

The value of item.trfsdt is a decimal . Sample of item.trfsdt = 181119 . I want to make it "Nov 19 2018" = 181119 .

  • 1
    You can try `momentjs` for client-side conversion from `yymmdd` format to JS `Date`, see this issue: https://stackoverflow.com/questions/41122493/convert-date-stringyymmdd-to-date-object-in-js. – Tetsuya Yamamoto Nov 19 '18 at 08:20

1 Answers1

1

If you are sure that the format is consistent and that the year >= 2000, then:

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

$.each(response, function (i, item) {
                    let pieces = ("" + item.trfsdt) // make sure it's a string
                                        .match(/\d{2}/g) // split it in pairs of two
                                        .map(n => parseInt(n)); // cast them back to int
                    let date = months[pieces[1] - 1] + " " + pieces[2] + " 20" + pieces[0]; // maybe use string interpolation?

                    // do what you have to do with the 'date' string

                    var tableData = "<tr><td><input type='checkbox' class='selectedCheckBox' data-value='" + item.trfbch + "'/></td><td>" + item.trfpon + "</td><td>" + item.dptnam + "</td><td>" + item.trfbch + "</td><td><button type='button' class='btn btn-primary deleteTrfBtn' data-value='" + item.trfbch + "'>Delete</button></td><td>" + item.trfsdt + "</td>";

                    $(".tablebodyinfo").append(tableData);

                });