so I ran into this little problem and I don't know how to solve it. I have two dates, one that comes from a Python script that arrives as a String, and one that comes from a MongoDB object. I need to compare them but the date coming from MongoDB seems to have a strange format that doesn't allow me to do so. This is an example of the dates formats:
String: 29/12/22 15:00
Object: Wed Dec 28 2022 15:00:00 GMT 0100 (hora estándar de Europa central)
From this I can easily transform the String coming from Python to a Date object, but what should I do with the MongoDB object to be able to compare them?
CodePudding user response:
You can use momentjs to format dates in javascript. He is an Example:
let date1 = "25/12/22 15:00"
let date2 = "Wed Dec 27 2022 15:00:00 GMT 0100"
if(moment(date1,'DD/MM/YY HH:mm') > new Date(date2)){
console.log('True')
} else {
console.log('false')
}
<script type = "text/JavaScript" src = " https://MomentJS.com/downloads/moment.js"></script>
CodePudding user response:
Here's a very longhand method: pass the mongo date as a string, split it into its components, and rebuild it. Here, it's rebuilt to the same format as your Python script produces.
function convert(mongoDateString) {
const monthAr = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const mongoDateAr = mongoDateString.split(" ");
const dayNo = mongoDateAr[2];
const monthNo = monthAr.indexOf(mongoDateAr[1]);
const yearNo = mongoDateAr[3];
const time = mongoDateAr[4].substring(0, mongoDateAr[4].length - 3);
return dayNo "/" monthNo "/" yearNo " " time;
}
let thisDateString = "Wed Dec 28 2022 15:00:00 GMT 0100 (hora estándar de Europa central)"
console.log(convert(thisDateString ))