Convert PHP TIME() to Datetime with Javascript

Asked

Viewed 194 times

0

How to convert a time() generated with a PHP for a Datetime style:

2015-07-14 21:42:44 
  • Did any of the answers help you? If not, comment on the answer stating the problem you face with it, if yes then mark the answer that helped you as correct by clicking on

2 answers

1


Alternative similar to that of @Lucky boy, but in this case we get days and months, days, hours, minutes and seconds below 10 will have a 0 in front:

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>

1

Use the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.