【问题标题】:Dataweave : Days passed and days left in current monthDataweave:当月过去的天数和剩余天数
【发布时间】:2020-06-08 10:29:47
【问题描述】:

我能够得到当月过去的天数。但不知道如何获取当前月份的剩余天数。

例如在这个月(六月)过去的天数=7,剩下的天数=23

%dw 2.0
output application/json
---
{
    "daysPassed" : now().day -1,
    "daysLeft" : ""
}

【问题讨论】:

    标签: dataweave mulesoft mule-esb


    【解决方案1】:

    DataWeave 似乎没有内置函数来计算月末,所以我使用一些日期算法来计算它。

    %dw 2.0
    output application/json
    fun daysLeftOnMonth(d) = do {
        var nextMonthDate = d as Date + |P1M|
        var endOfMonth= ( nextMonthDate  - ( ("P$(nextMonthDate.day as String)D" as Period) )).day
        ---
        endOfMonth - d.day + 1 
    }
    ---
    {
        "daysPassed" : now().day - 1,
        "daysLeft" : daysLeftOnMonth(now())
    }
    

    为了更详细地解释,首先我在当前日期上加一个月:

    var nextMonthDate = d as Date + |P1M|
    

    然后我去月初,少了一天,所以我得到了当月的最后一天:

    nextMonthDate  - (("P$(nextMonthDate.day as String)D" as Period)
    

    诀窍是如何在 DataWeave 中休息一个动态时间段。我不得不寻找它。您必须将句点构造为字符串,然后将其强制转换为句点。

    然后我只是将经过的天数减去该月最后一天的天数。

    【讨论】:

    • 这非常有效,即使对于 2 月的闰年也是如此。如果你不介意你能解释一下这两行。我似乎无法绕过它。什么是|P1M| ? var nextMonthDate = d 作为日期 + |P1M| var endOfMonth= ( nextMonthDate - ( ("P$(nextMonthDate.day as String)D" as Period) )).day
    • 当然,我已经用解释更新了答案。
    【解决方案2】:

    与此类似,您始终可以在其中构建闰年检查。

    %dw 2.0
    output application/json
    var thirtyDayMonths = [4,6,8,10]
    ---
    {
        "daysPassed" : now().day -1,
        "daysLeft" : if (thirtyDayMonths contains now().month) 
                             (30-now().day) 
                     else if (now().month == 2) 
                             (28-now().month) 
                     else (31-now().month)
    }
    

    【讨论】:

    • 我认为将闰年排除在外并不是一个好主意。
    • 就像我说的,它总是可以被构建出来的。我从来没有提到将它排除在解决方案的范围之外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多