1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Eav\Model\Entity\Attribute\Backend;
/**
* @api
* @since 100.0.2
*/
class Datetime extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
{
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
*/
protected $_localeDate;
/**
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
* @codeCoverageIgnore
*/
public function __construct(\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate)
{
$this->_localeDate = $localeDate;
}
/**
* Formatting date value before save
*
* Should set (bool, string) correct type for empty value from html form,
* necessary for further process, else date string
*
* @param \Magento\Framework\DataObject $object
* @throws \Magento\Framework\Exception\LocalizedException
* @return $this
*/
public function beforeSave($object)
{
$attributeName = $this->getAttribute()->getName();
$_formated = $object->getData($attributeName . '_is_formated');
if (!$_formated && $object->hasData($attributeName)) {
try {
$value = $this->formatDate($object->getData($attributeName));
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\LocalizedException(__('Invalid date'));
}
if ($value === null) {
$value = $object->getData($attributeName);
}
$object->setData($attributeName, $value);
$object->setData($attributeName . '_is_formated', true);
}
return $this;
}
/**
* Prepare date for save in DB
*
* string format used from input fields (all date input fields need apply locale settings)
* int value can be declared in code (this meen whot we use valid date)
*
* @param string|int|\DateTimeInterface $date
* @return string
*/
public function formatDate($date)
{
if (empty($date)) {
return null;
}
// unix timestamp given - simply instantiate date object
if (is_scalar($date) && preg_match('/^[0-9]+$/', $date)) {
$date = (new \DateTime())->setTimestamp($date);
} elseif (!($date instanceof \DateTimeInterface)) {
// normalized format expecting Y-m-d[ H:i:s] - time is optional
$date = new \DateTime($date);
}
return $date->format('Y-m-d H:i:s');
}
}