【问题标题】:How to compare two dates in Postman如何在邮递员中比较两个日期
【发布时间】:2019-12-19 10:57:24
【问题描述】:

我有一个场景,我需要将 API 响应中的日期与今天的日期进行比较,并检查它是否小于或等于。

API 响应将为我提供一个 JSON 对象,并且在该 JSON 中,密钥“许可证”将包含格式为“2019 年 8 月 13 日”的日期,我需要将此日期与今天的日期进行比较,如果今天的日期是大于“13-Aug-2019”会导致测试结果失败。

下面是我编写的代码,用于获取许可证字符串中的日期和今天的日期,

Var body = JSON.parse(response Body);
Var body date=body["license"]
//Sample license value is " license cs code1 version 13-aug- 
2018 cnts ......"
var words = bodydate.split(' ');
license_valid_till=words[4]; // This will get the string 13-aug- 
2019

console.log(license_valid_till)

var ts = new Date();
var part=ts.toDateString();
var dpart = part.split(' ');
today_date=dpart[2] + "-" +dpart[1] +"-"+ dpart[3];
//This will get the string 12-aug-2019
console.log(today_date)

现在我的问题是如何比较这两个值,有什么建议会有很大帮助吗?

【问题讨论】:

    标签: javascript postman postman-collection-runner


    【解决方案1】:

    你可以使用momentjs。

    var moment = require('moment')
    

    momentjs 使用示例:https://jsfiddle.net/onigetoc/rzyz4wgp/

    【讨论】:

      【解决方案2】:

      如果您想在没有任何第三方库的情况下执行此操作,则可以使用以下代码 sn-p。

      pass=true;
      fail=false;
      var responseDate = "13-Aug-2019";
      var currentDate;
      var months = ['Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
      
      if(responseCode.code === 204){
      var today = new Date();
      var dd = today.getDate();
      var MMM = months[today.getMonth()];
      var yyyy = today.getFullYear();
      today = dd+'-'+MMM+'-'+yyyy;
      console.log("Current Time for event is -> "+today);
      
      if(responseDate === today){
          console.log("Pass");
          tests["ResponseDate and current date does matched "+responseDate] = responseDate === today;
      }else{
          console.log("Fail");
          tests["ResponseDate and current date does not matched "+responseDate] = responseDate !== today;
      }
      }else{
      console.log("Request failed ...!");
      }
      

      您可以将 responseDate 值替换为运行时响应日期值。 您可以使用 if 条件来检查大于、等于或小于操作。

      【讨论】:

        【解决方案3】:

        我们有同样的需求,所以,我们将分享我们的完整解决方案。 它使用 postman 的 Test 选项运行,在这种情况下,它确实使用 get 中的数据并使用 Moment.js 对其进行处理,基本上:

        1. 使用 Get 检索数据
        2. 检查 JSON 响应是否正常
        3. 加载 moment.js
        4. 将日期值加 20 天
        5. 比较一下日期比今天大
        6. 创建一个包含选定记录的数组
        7. 发布到 Restfull 数据库(您可以使用 http://restdb.io 测试 Get 和 Post)

        测试代码示例

        var moment = require('moment');
        pm.test("response must be valid and have a body", function () {
             pm.response.to.be.ok; 
             pm.response.to.be.withBody;
             pm.response.to.be.json;
        });
        var slots = pm.response.json();
        var myPost = [];
        var todo = [
            {
              "_id": "5d13e83bb1c3633400002841"
            }
          ];
        var hoje = moment();
        for (let thisItem of slots) {
            var changedOk = moment(thisItem._changed).add(20, 'days');
            if (moment(changedOk).isBefore(hoje))
            myPost.push( {
                _id: thisItem._id,
                toDo : todo,
                approved: true,
                onHalt: true,
                p: false        
            });
        }
        console.log(myPost);
        pm.sendRequest({
            url: 'https://mydbase-0000.restdb.io/rest/slots',
            method: 'POST',
            header:    { 'cache-control': 'no-cache',
                        'content-type': 'application/json',
                        'x-apikey': 'xxxxxxxxxxxxxxxxxxxxxx'},
            body: {
                mode: 'raw',
                raw: JSON.stringify(myPost)
            }
        }, function (err, res) {
            console.log(res);
        });
        

        【讨论】:

          【解决方案4】:

          您可以使用 Postman echo API 来执行此操作 - 请查看给定的链接,看看这是否是您要查找的内容。

          https://docs.postman-echo.com/?version=latest#b709b99c-3347-40fc-2c21-98ceb7f9e267

          【讨论】:

            【解决方案5】:

            我有一个类似的场景:我需要在邮递员中比较两个日期,日期格式如“2022-01-16T19:40:51.816”。

            所以我用这个:

            // (dates from JSON for my case)
            // var date1 = "2022-01-16T19:40:51.816";
            // var date2 = "2022-01-16T17:40:51.816";
            // (today for your case)
            // var today = new Date();
            pm.expect(Date.parse(date1)).to.be.above(Date.parse(date2));
            

            【讨论】:

              猜你喜欢
              • 2011-01-13
              • 2021-08-17
              • 2011-04-20
              • 1970-01-01
              • 2022-01-05
              • 2016-06-25
              相关资源
              最近更新 更多