0

JSFiddle: https://jsfiddle.net/u8w3v9fd/1/

I am trying to get the day, month and year from a date that is passed form the database in the format: DD/MM/YYYY. However I can't even seem to get the correct date to show.

Here is my code:

var time = "1522843537";

var regDateOriginal = new Date(time);
var regDate = new Date();
regDate.getMonth(regDateOriginal);
regDate.getHours(regDateOriginal);
regDate.getDate(regDateOriginal);

document.write("<p style='color: #fff'>" + regDate.getDate(regDateOriginal) + "</p>");

As you can see, this is returning:

21

Which is todays date. It should be 4

I have googled it and hacked around with various versions for the past 45 mins. I am a junior and would really appreciated a nicely commented piece of code so I can learn instead of just copying and pasting.

Thank you for your help.

Community
  • 1
  • 1
modusTollens
  • 397
  • 7
  • 23
  • getMonth, getHours, and getDate have no parameters. – meyi May 21 '18 at 14:59
  • 2
    You have "googled it"? Really? What reference did you find that says that using any of those date functions in that way would return what you think it should? [Date.prototype.getDate()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate). Those methods take no arguments and operate on the "date" that the date object was created from. – gforce301 May 21 '18 at 15:01
  • You need to multiply *time* by 1000 to convert from seconds to milliseconds. And you need `regDateOriginal.getDate()`. The *getDate* method takes no parameters, so you're getting the date for *regDate*, which is the host's current date. – RobG May 22 '18 at 08:57

1 Answers1

-1

From here

var time = 1522843537;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(time);
console.log(d.getDate());

Of course, you can still do all the other Date functions as needed.

meyi
  • 7,574
  • 1
  • 15
  • 28
  • Sorry for late reply and acceptance. Thank you very much for your help. – modusTollens May 22 '18 at 07:47
  • `new Date(time*1000).getDate()` will achieve an identical result in one line of code rather than 3. The value is a UNIX timestamp, which is seconds since 1970-01-01 whereas javascript uses milliseconds, so it must be multiplied by 1000. You should have marked this as a duplicate. – RobG May 22 '18 at 08:58