1

How can I check if a product is new in Magento 2?

I found this solution for Magento 1:

function isProductNew(Mage_Catalog_Model_Product $product)
{
    $newsFromDate = $product->getNewsFromDate();
    $newsToDate   = $product->getNewsToDate();
    if (!$newsFromDate && !$newsToDate) {
        return false;
    }
    return Mage::app()->getLocale()
            ->isStoreDateInInterval($product->getStoreId(), $newsFromDate, $newsToDate);
}

How can I migrate this code to make it work in Magento 2 ?

1 Answer 1

2

Propably the best option is to add new helper with following code:

<?php

namespace Vendor\Module\Helper;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product as ModelProduct;
use Magento\Store\Model\Store;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

class HelperName extends \Magento\Framework\Url\Helper\Data
{

    /**
     * @var TimezoneInterface
     */
    protected $localeDate;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        TimezoneInterface $localeDate
    ) {
        $this->localeDate = $localeDate;
        parent::__construct($context);
    }

    public function isProductNew(ModelProduct $product)
    {
        $newsFromDate = $product->getNewsFromDate();
        $newsToDate = $product->getNewsToDate();
        if (!$newsFromDate && !$newsToDate) {
            return false;
        }

        return $this->localeDate->isScopeDateInInterval(
            $product->getStore(),
            $newsFromDate,
            $newsToDate
        );
    }
}

Then in .phtml file use this:

$helper = $this->helper('Vendor\Module\Helper\HelperName');

and in products foreach:

<?php if($helper->isProductNew($_product)): ?>
    Your label code here
<?php endif; ?>
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.