Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

shopify - Date Math / Manipulation in Liquid Template Filter

I'm constructing an "Integration URL" in Desk.com, which uses the Shopify Liquid Template filter syntax. This URL needs to contain a "start date" and an "end date" for a query where the start date is 7 days ago and the end date is right now.

To achieve this I think I need to subtract 7 days (604800 in Epoch time) from the 'now' object and then apply my formatting but I can't figure out valid syntax for that.

For the current time, this syntax is valid and working:

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

For 7 days ago, here's the best I could come up with (isn't working):

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

Any suggestions on a valid syntax for "7 days ago" in Liquid? Would greatly appreciate any advice!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"}}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...