-1

The db table has column "lastlogin" saved in date format e.g. 2014-03-15 15:45:58.

Into the JSON [Object] is : lastlogin: "2014-03-15 15:46:58"

I need to display this value in format "15/03/2015 15:45:58" into my html table
and i don't need to alter this value inside a JSON [Object].

I want doing this with pure javascript code without using a library like moment.js, Date.js etc etc.

I write my code but there is another more practice code ?

my javascript code

function usersList() { 
$('#idsearch').attr("placeholder", "Find user by ID");
$('#my-table').empty();
$('#sectiontitle').html('Users list');
$('#my-table').append('<tbody><tr><th>Last login</th></tr></tbody>');

  $.getJSON('../../functions/users.php' , function(result) {

      $.each(result, function(index, array){

        var dateSplit = array['lastlogin'].split(" ");
        // create new array with 2 values
        // N.B. if the value was 2014-03-15T15:46:58 i use .split("T")

        var time = dateSplit[1]; // note the [1] for the second value in array dateSplit
        // create a var for the time value only ["15:46:58"]

        var dateSplit2 = dateSplit[0].split("-"); // note the [0] for the first value in array dateSplit
        // create a new array with 3 value ["2014", "03", "15"]

        var date = dateSplit2.reverse().join('/');
        // create a date var with values reversed and joined ["15/03/2014"]

$('#my-table > tbody:last').append('<tr><td>'+date+' '+time+'<td></tr>'); // show 15/03/2014 15:46:58

     });
  });
}
geomo
  • 139
  • 1
  • 1
  • 15

1 Answers1

1

Format with correct functions. Dont split, use Date:

 var date = new Date("2014-03-15 15:45:58"); // Replace with Database-Entry

http://www.w3schools.com/jsref/jsref_obj_date.asp

Example:

function usersList() { 
    $('#idsearch').attr("placeholder", "Find user by ID");
    $('#my-table').empty();
    $('#sectiontitle').html('Users list');
    $('#my-table').append('<tbody><tr><th>Last login</th></tr></tbody>');

    $.getJSON('../../functions/users.php' , function(result) {
        $.each(result, function(index, array) {
            $('#my-table > tbody:last').append('<tr><td>' + formatDate('d/m/Y H:i:s', new Date(array['lastlogin'])) '<td></tr>'); // show var date and time
        });
    });
}

function formatDate(format, date) {
    format = format.replace(/Y/g, date.getFullYear());
    format = format.replace(/m/g, date.getMonth());
    format = format.replace(/d/g, date.getDay());
    format = format.replace(/H/g, date.getHours());
    format = format.replace(/i/g, date.getMinutes());
    format = format.replace(/s/g, date.getSeconds());
    return format;
}
Adrian Preuss
  • 3,228
  • 1
  • 23
  • 43