Fix code to take local date and time

2

I am doing a query with javascript to be able to get the local date and time of my laptop but my problem is that it takes me the month as 4 and not 04 which is the one I need, please could you help me, thank you very much and here I show you the code to get the date and time

var d = new Date();
var m = d.getMonth() + 1;
var mes = (m < 10) ? +0+ + m : m;
d = (d.getFullYear()+'-'+mes+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
console.log(d);

If you look at the console, take it for example to me: 28-4-2018 10:32:50 but I need 4 as 04, I appreciate your help

    
asked by Juan Esteban Yarce 28.04.2018 в 17:33
source

2 answers

3

I give you a little ugly option but it works. I added a "0" in front of the month. I hope it helps you. You also have Moments link where you will find information for the topic of dates.

var d = new Date();
var m = d.getMonth() + 1;
var mes = (m < 10) ? +0+ + m : m;
d = (d.getFullYear()+'-'+'0'+mes+'-'+d.getDate()+''+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
                console.log(d);
VM656:5 2018-04-28 18:16:56
You can also do it in the following somewhat prettier way by using inverted commas "''" and placing each variable inside "{}" with the weights in front ($):

var d = new Date()
var m = d.getMonth() + 1;
var mes = (m < 10) ? +0 + + m : m;
d = (d.getFullYear()+'- 0${mes}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}')
console.log(d)
    
answered by 28.04.2018 в 18:20
0

You could do it with toISOString ().

var d = new Date();
var n = d.toISOString();
document.write(n);
  

Source: W3schools

Or you could use the one in this Post Convert ISO date to international date type javascript

<html>
<script>
  var myDate = new Date();
  var thisMonth = new Date(myDate.getFullYear(), myDate.getMonth(), 1);
  var nextMonth = new Date(myDate.getFullYear(), myDate.getMonth() + 2, 0);

  console.log("Formatted date start: " + formatDate(thisMonth));
  console.log("Formatted date end: " + formatDate(nextMonth));

  function padLeft(n){
    return ("00" + n).slice(-2);
  }

  function formatDate(){        
    var d = new Date,
        dformat = [ d.getFullYear(),
                    padLeft(d.getMonth()+1),
                    padLeft(d.getDate())
                    ].join('-')+
                    ' ' +
                  [  padLeft(d.getHours()),
                     padLeft(d.getMinutes()),
                     padLeft(d.getSeconds())].join(':');
     return dformat
  }

</script>
</html>
  

Source: Convert ISO date to international date type javascript   

    
answered by 28.04.2018 в 20:47