Date Math / Manipulation in Liquid Template Filter

限于喜欢 提交于 2019-11-30 08:22:16

Much thanks to @iveskev from the Desk.com "WOW" team for this answer:

If you do {{'now'}} it returns the string “now” not a timestamp for the current time. So if you do {{'now' | minus: 604800 }} it returns “-604800” not the current unix time minus 604800. When you use the date filter, then liquid picks up that you are referencing the current time and outputs the time as a string. However even if we get ‘now’ to output the current date, we are still subtracting from a string and so will be returned with “-604800”. The only time that math on a string works correctly is if the sting is only a number.

So in order to get the correct date we first have to get the unix timestamp for now, do the subtraction, then reformat to the desired formate. You can use %s to get unix time. So to get the current time in unix it would be: {{'now' | date: '%s' }}

At that point you can then do the subtraction and then format the time in the correct way. We can do this all at once in the following statement:

{{'now' | date: "%s" | minus : 604800 | date: "%b %d, %Y %I:%M %p -0500" | uri_encode | replace:"+","%20"}}

for those using liquidjs I couldn't find a way without having a new filter, so I made one:

daysAgo = (input) ->
  date = new Date()
  date.setDate(date.getDate() - parseInt(input, 10))
  date

parser.registerFilter('days_ago', (value) -> daysAgo(value))

then doing:

{{ 1 | day_ago | date "%Y-%m-%d" }}
2019-05-02

I've posted an issue on the liquidjs repo: https://github.com/harttle/liquidjs/issues/125

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!