skip to Main Content

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?

3

Answers


  1. 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>
    Login or Signup to reply.
  2. 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 ))
    Login or Signup to reply.
  3. Based on the information the value from MongoDB (here: date2) is not a string, it is a Date object. Thus you need to convert only the value from Python (here: date1):

    if ( moment(date1, 'DD/MM/YY HH:mm').toDate() > date2 ) {
       console.log('true')
    } else {
       console.log('false')
    }
    

    Or, if you prefer to work with Moment objects:

    moment(date1, 'DD/MM/YY HH:mm').isAfter(moment(date2))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search