-2

I want to calculate DaysSinceLastLogin, and want to use the below functionality(Found on google):

const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));

So with my scenario, My firstdate format is in string: "2020-03-06 18:20:36:187" and the secondDate would be today's date so basically I need the firstDate and secondDate to be passed in the above function but format is different, how can I convert firstdate and today's date in the required format?

Divya Agrawal
  • 300
  • 1
  • 2
  • 15

1 Answers1

1

The Date Object constructor accepts a date string as the first parameter. If the constructor is used without any parameters it will be initialised with the current date.

const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const lastLoginDate = new Date("2020-03-06 18:20:36:187");
const todaysDate = new Date(); // Current date
const diffDays = Math.round(Math.abs((lastLoginDate - todaysDate) / oneDay));

I would however recommend using a library such as moment.js to handle DateTime manipulation in javascript since even the Mozilla documentation recommends against using the DateTime Object for string conversion:

Note: Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

Alternatively you could handle DateTime manipulation on the server side (with PHP for example) to ensure a consistent user experience

Finally I will also refer to this answer which goes into more details about parsing Date strings in JS and is perhaps what you should have searched for originally rather than creating a new question.

Henry Howeson
  • 677
  • 8
  • 18
  • If `new Date()` is not sufficient because it returns the hours, minutes, seconds..., then [this answer](https://stackoverflow.com/questions/25445377/how-to-get-current-date-without-time) can help. Just do `todaysDate.setHours(0,0,0,0)` and it set any time to 0, giving the pure date. – E. Zacarias Mar 09 '20 at 11:55
  • 1
    @Liam I decided to post the solution first while I was writing up the explanation incase the OP was after a quick response. I have now updated my answer. – Henry Howeson Mar 09 '20 at 12:03