Reputation: 6936
I have a date timestamp stored in mysql which is like 2017-06-29 08:37:31
I am getting it through AJAX and I want to compare it with current date, whether it is same or not.
My code is
let dateStamp = moment(this.notificationData[0].notification_timestamp).format('LL');//date/timestamp from mysql received in json
let dateToday = moment().format('LL');//current date
console.log(dateStamp,dateToday)
console.log(moment(dateToday).diff(dateStamp,'days'))//comparison
Though I am getting the result in .diff(). I want to know if there is any other correct way of doing this.
Timezone is not an issue I think for me. Just date comparison.
Thanks
Upvotes: 3
Views: 9875
Reputation: 69
You can always write logic yourself and not depend on external libraries.
If you want to continue to use external logic, try out one of the libraries the momentjs team recommends. https://momentjs.com/docs/#/-project-status/
If you want to write your own logic, try to use the Date()
object.
const now = new Date();
const dateString = now.toLocaleDateString();
const timeString = now.toLocaleTimeString();
// will create new date object with the timestamp
const dateFromApi = new Date(timestamp)
after that you are free to write whatever comparison logic you need.
Upvotes: 1
Reputation: 248
You can compare them directly.
var date = moment("2017-07-11")
var now = moment();
if (now > date) {
// date is past
} else {
// date is future
}
You can also use isBefore, isSame, and isAfter.
Upvotes: 0