Search code examples
javascriptdatetimeline-breaks

Add line break inside a function


I have got a problem with adding a line break inside my function. The function displays date and time. I need to display date on the fisrt line and time on the second. I have checked all the related answers. I have tried to use \n, br, join("\n"), tried to create br element inside my function, but unfortunately it did not work. Here is a piece of my code:

function getTime(a)
{ 
  var d;
  if(a) {
    d = new Date(a);
  } else {
    d = new Date();
  }
  return ('0' + d.getDate()).slice(-2) + '.'+
         ('0' + (d.getMonth() + 1)).slice(-2) + '.' + 
         (d.getYear() + 1900) + ' ' + // here instead of space I need to add a line break in order to display time on a new line 
         ('0' + d.getHours()).slice(-2) + ':' +
         ('0' + d.getMinutes()).slice(-2) + ':' + 
         ('0' + d.getSeconds()).slice(-2) + '.' + 
         d.getMilliseconds();
}

Please, give me the hint how to solve the problem. Thank you very much in advance!


Solution

  • You can add a newline char:

    function getTime(a)
    { 
      var d;
      if(a) {
        d = new Date(a);
      } else {
        d = new Date();
      }
      return ('0' + d.getDate()).slice(-2) + '.'+
             ('0' + (d.getMonth() + 1)).slice(-2) + '.' + 
             (d.getYear() + 1900) + '\n' + // here instead of space I need to add a line break in order to display time on a new line 
             ('0' + d.getHours()).slice(-2) + ':' +
             ('0' + d.getMinutes()).slice(-2) + ':' + 
             ('0' + d.getSeconds()).slice(-2) + '.' + 
             d.getMilliseconds();
    }
    
    console.log(getTime())

    or if you want in markup inner html you add <br>

        function getTime(a)
        { 
          var d;
          if(a) {
            d = new Date(a);
          } else {
            d = new Date();
          }
          return ('0' + d.getDate()).slice(-2) + '.'+
                 ('0' + (d.getMonth() + 1)).slice(-2) + '.' + 
                 (d.getYear() + 1900) + ' <br> ' + // here instead of space I need to add a line break in order to display time on a new line 
                 ('0' + d.getHours()).slice(-2) + ':' +
                 ('0' + d.getMinutes()).slice(-2) + ':' + 
                 ('0' + d.getSeconds()).slice(-2) + '.' + 
                 d.getMilliseconds();
        }
    
    document.querySelector('.test').innerHTML = getTime()
    <div class='test'></div>

    if your dealing with html markup <br> tag is the correct way to display a carriage return.