-1

The following piece of code is used to generate the current date in format YY/MM/DD and dateTime correctly stores 2017/11/4 and 2017/11/4 is correctly stored in my database, however when I try to print it on my page I get Sat Nov 04 2017 00:00:00 GMT+0200 (FLE Standard Time)

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var dateTime = year + "/" + month + "/" + day;

How I print it on my page:

    <%- include('header' ,{ title:"Bozhidar", userId }) -%>

    <div class='wrapper'>

    <%   for (var i = 0; i < results.length; i++) {  %>

    <div class='container'>
        <div class='stickyContainer homePage'>
            <h1 class='imageTitle'><%= results[i].name %></h1>
            <img class='uploadedRealImage' src='/images/Uploads/<%= results[i].path %>' alt='Random image' />

            <%  if (userId == results[i].author) { %>

            <form id='deleteImageForm' method='POST' action=''>
                <input type='hidden' name='id' value=''>
                <input type='hidden' name='path' value=''>
                <input type='hidden' name='author' value=''>
                <button id='delImage' type='submit' name='imageDelete'>X</button>
            </form>

            <%  }   %>

        </div>
        <h1><%= results[i].author %></h1>
        <p><%= results[i].date %></p>
        <p><%= results[i].views %></p>
    </div>

    <%   }   %>

    </div>

<%- include('footer') -%>
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • 3
    That's how JavaScript formats date values. It's what `.toString()` returns from a Date instance. – Pointy Nov 04 '17 at 13:23
  • So how do I fix it in my case? – Onyx Nov 04 '17 at 13:28
  • 1
    Where does `results[i].date` come from, and what is its value? How is this related to the rest of the code? What template engine is that? – Bergi Nov 04 '17 at 13:33
  • I'm using EJS, and results[i].date is the result of the database query that gives me all the information about the image. I updated my code. – Onyx Nov 04 '17 at 13:36

1 Answers1

0
function changeDate(date){
  var dateObj = new Date(date);
  var month = dateObj.getUTCMonth() + 1;
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();
  var dateTime = year + "/" + month + "/" + day;
  return dateTime;
}

HTML

<p><%= changeDate(results[i].date) %></p>

Call the function in html.

Escoute
  • 386
  • 4
  • 17