Ad

Adding Days To A Date Excluding Weekends In Shopify

- 1 answer

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?

Ad

Answer

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 %}
Ad
source: stackoverflow.com
Ad