Adding days to a date excluding weekends in Shopify

帅比萌擦擦* 提交于 2020-06-26 08:46:56

问题


I'm trying to write some code to estimate a shipping date in Shopify. I've been learning liquid but am having trouble writing some logic in Ruby. I'm not sure if Shopify templates use Ruby or Ruby on Rails.

I want to get todays date and add either 3 or 5 days based on a input variable, excusing weekends. Heres how I'd do it in PHP:

$orderDate = date('Y-m-d');
$personalized = true;

$orderDays = ($personalized ? 4 : 2);
(date('H') > 12 ? $orderDays++ : $false);

$d = new DateTime( $orderDate );
$t = $d->getTimestamp();

// loop for X days
for($i=0; $i<$orderDays; $i++){

    // add 1 day to timestamp
    $addDay = 86400;
    // get what day it is next day
    $nextDay = date('w', ($t+$addDay));
    // if it's Saturday or Sunday get $i-1
    if($nextDay == 0 || $nextDay == 6) {
        $i--;
    }
    // modify timestamp, add 1 day
    $t = $t+$addDay;

}

$d->setTimestamp($t);
echo $d->format( 'Y-m-d' ). "\n";

Whats the best way to write this for Shopify liquid?


回答1:


Use the date filter in Liquid.

The date format you are using in Ruby is equivalent to:

{{ "now" | date: "%Y, %m, %-d" }}

A day is 86400 seconds. Example to add 3 days from now and format:

{% assign days = 3 | times: 86400 %}
{{ "now" | date: "%s" | plus: days | date: "%Y, %m, %-d" }}

Note: You need the date: "%s" filter applied first to "now" for Liquid to understand that you are using the current timestamp and not the string "now".

A way to check if an order is made on a weekend would be:

{% assign wday = order.created_at | date: "%a" %}
{% if wday == 'Sat' or wday == 'Sun' %}
    el Weekendo
{% endif %}


来源:https://stackoverflow.com/questions/39730058/adding-days-to-a-date-excluding-weekends-in-shopify

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