Convert TIME () from PHP to DateTime with JavaScript

0

How to convert a time() generated with a PHP to a DateTime style this:

2015-07-14 21:42:44 
    
asked by anonymous 03.07.2015 / 01:47

2 answers

1

Alternative similar to @FelipeDouradinho , but in this case we get days and months, days, hours, minutes and seconds under 10 will have 0 ahead:

var date = new Date(<?php echo $_SERVER['REQUEST_TIME']; ?> * 1000);
var ano  = date.getFullYear();
var mes  = date.getMonth() + 1;
var dia  = date.getDate();
var hora = date.getHours();
var min  = date.getMinutes();
var seg  = date.getSeconds();

mes  = mes  > 9 ? mes  : ("0" + "" + mes);
dia  = dia  > 9 ? dia  : ("0" + "" + dia);
hora = hora > 9 ? hora : ("0" + "" + hora);
min  = min  > 9 ? min  : ("0" + "" + min);
seg  = seg  > 9 ? seg  : ("0" + "" + seg);

data = ano + "-" + mes + "-" + dia + " " + hora + ":" + min + ":" + seg;

console.log(data);

function formatDate(time) {
    var date = new Date(time * 1000);
    var ano  = date.getFullYear();
    var mes  = date.getMonth() + 1;
    var dia  = date.getDate();
    var hora = date.getHours();
    var min  = date.getMinutes();
    var seg  = date.getSeconds();

    mes  = mes  > 9 ? mes  : ("0" + "" + mes);
    dia  = dia  > 9 ? dia  : ("0" + "" + dia);
    hora = hora > 9 ? hora : ("0" + "" + hora);
    min  = min  > 9 ? min  : ("0" + "" + min);
    seg  = seg  > 9 ? seg  : ("0" + "" + seg);

    data = ano + "-" + mes + "-" + dia + " " + hora + ":" + min + ":" + seg;

   return data;
}

var btn     = document.getElementById("myButton");
var target  = document.getElementById("target");

btn.onclick = function() {
    target.innerHTML = formatDate(1435881123);    
};
<div id="target"></div>
<button id="myButton">Testar</button>
    
04.07.2015 / 14:59
1

Use Date to do this:

<script type="text/javascript">
    var data = new Date(<?php echo time(); ?> * 1000);
    data = ""+data.getFullYear()+"-"+(data.getMonth() + 1)+"-"+data.getDate()+" "+data.getHours()+":"+data.getMinutes()+":"+data.getSeconds()+"";

    alert(data);
</script>

Example:

// Formato 2015-07-14 21:42:44

var data = new Date(1435881123 * 1000);
data = ""+data.getFullYear()+"-"+(data.getMonth() + 1)+"-"+data.getDate()+" "+data.getHours()+":"+data.getMinutes()+":"+data.getSeconds()+"";

alert(data);

jsfiddle

    
03.07.2015 / 01:51