DateTime#

NAME#

Kernel::System::DateTime - Handles date and time calculations.

DESCRIPTION#

Handles date and time calculations.

PUBLIC INTERFACE#

new()#

Creates a DateTime object. Do not use new() directly, instead use the object manager:

# Create an object with current date and time
# within time zone set in SysConfig OTRSTimeZone:
my $DateTimeObject = $Kernel::OM->Create(
    'Kernel::System::DateTime'
);

# Create an object with current date and time
# within a certain time zone:
my $DateTimeObject = $Kernel::OM->Create(
    'Kernel::System::DateTime',
    ObjectParams => {
        TimeZone => 'Europe/Berlin',        # optional, TimeZone name.
    }
);

# Create an object with a specific date and time:
my $DateTimeObject = $Kernel::OM->Create(
    'Kernel::System::DateTime',
    ObjectParams => {
        Year     => 2016,
        Month    => 1,
        Day      => 22,
        Hour     => 12,                     # optional, defaults to 0
        Minute   => 35,                     # optional, defaults to 0
        Second   => 59,                     # optional, defaults to 0
        TimeZone => 'Europe/Berlin',        # optional, defaults to setting of SysConfig OTRSTimeZone
    }
);

# Create an object from an epoch timestamp. These timestamps are always UTC/GMT,
# hence time zone will automatically be set to UTC.
#
# If parameter Epoch is present, all other parameters will be ignored.
my $DateTimeObject = $Kernel::OM->Create(
    'Kernel::System::DateTime',
    ObjectParams => {
        Epoch => 1453911685,
    }
);

# Create an object from a date/time string.
#
# If parameter String is given, Year, Month, Day, Hour, Minute and Second will be ignored
my $DateTimeObject = $Kernel::OM->Create(
    'Kernel::System::DateTime',
    ObjectParams => {
        String   => '2016-08-14 22:45:00',
        TimeZone => 'Europe/Berlin',        # optional, defaults to setting of SysConfig OTRSTimeZone
    }
);

# Following formats for parameter String are supported:
#
#   yyyy-mm-dd hh:mm:ss
#   yyyy-mm-dd hh:mm                # sets second to 0
#   yyyy-mm-dd                      # sets hour, minute and second to 0
#   yyyy-mm-ddThh:mm:ss+tt:zz
#   yyyy-mm-ddThh:mm:ss+ttzz
#   yyyy-mm-ddThh:mm:ss-tt:zz
#   yyyy-mm-ddThh:mm:ss-ttzz
#   yyyy-mm-ddThh:mm:ss [timezone]  # time zone will be deduced from an optional string
#   yyyy-mm-ddThh:mm:ss[timezone]   # i.e. 2018-04-20T07:37:10UTC

Get()#

Returns hash ref with the date, time and time zone values of this object.

my $DateTimeSettings = $DateTimeObject->Get();

Returns:

my $DateTimeSettings = {
    Year      => 2016,
    Month     => 1,                 # starting at 1
    Day       => 22,
    Hour      => 16,
    Minute    => 35,
    Second    => 59,
    DayOfWeek => 5,                 # starting with 1 for Monday, ending with 7 for Sunday
    TimeZone  => 'Europe/Berlin',
};

Set()#

Sets date and time values of this object. You have to give at least one parameter. Only given values will be changed. Note that the resulting date and time have to be valid. On validation error, the current date and time of the object won’t be changed.

Note that in order to change the time zone, you have to use function `ToTimeZone()`_.

# Setting values by hash:
my $Success = $DateTimeObject->Set(
    Year     => 2016,
    Month    => 1,
    Day      => 22,
    Hour     => 16,
    Minute   => 35,
    Second   => 59,
);

# Settings values by date/time string:
my $Success = $DateTimeObject->Set( String => '2016-02-25 20:34:01' );

If parameter String is present, all other parameters will be ignored. Please see `new()`_ for the list of supported string formats.

Returns:

$Success = 1;    # On success, or false otherwise.

Add()#

Adds duration or working time to date and time of this object. You have to give at least one of the valid parameters. On error, the current date and time of this object won’t be changed.

my $Success = $DateTimeObject->Add(
    Years         => 1,
    Months        => 2,
    Weeks         => 4,
    Days          => 34,
    Hours         => 2,
    Minutes       => 5,
    Seconds       => 459,

    # Calculate "destination date" by adding given time values as
    # working time. Note that for adding working time,
    # only parameters Seconds, Minutes, Hours and Days are allowed.
    AsWorkingTime => 0, # set to 1 to add given values as working time

    # Calendar to use for working time calculations, optional
    Calendar => 9,
);

Returns:

$Success = 1;    # On success, or false otherwise.

Subtract()#

Subtracts duration from date and time of this object. You have to give at least one of the valid parameters. On validation error, the current date and time of this object won’t be changed.

my $Success = $DateTimeObject->Subtract(
    Years     => 1,
    Months    => 2,
    Weeks     => 4,
    Days      => 34,
    Hours     => 2,
    Minutes   => 5,
    Seconds   => 459,
);

Returns:

$Success =  1;  # On success, or false otherwise.

Delta()#

Calculates delta between this and another DateTime object. Optionally calculates the working time between the two.

my $Delta = $DateTimeObject->Delta( DateTimeObject => $AnotherDateTimeObject );

Note that the returned values are always positive. Use the comparison functions to see if a date is newer/older/equal.

# Calculate "working time"
ForWorkingTime => 0, # set to 1 to calculate working time between the two DateTime objects

# Calendar to use for working time calculations, optional
Calendar => 9,

Returns:

my $Delta = {
    Years           => 1,           # Set to 0 if working time was calculated
    Months          => 2,           # Set to 0 if working time was calculated
    Weeks           => 4,           # Set to 0 if working time was calculated
    Days            => 34,          # Set to 0 if working time was calculated
    Hours           => 2,
    Minutes         => 5,
    Seconds         => 459,
    AbsoluteSeconds => 42084759,    # complete delta in seconds
};

Compare()#

Compares dates and returns a value suitable for using Perl’s sort function (-1, 0, 1).

my $Result = $DateTimeObject->Compare( DateTimeObject => $AnotherDateTimeObject );
You can also use this as a function for Perl’s sort:

my @SortedDateTimeObjects = sort { $a->Compare( DateTimeObject => $b ) } @UnsortedDateTimeObjects;

Returns:

my $Result = -1;       # if date/time of $DateTimeObject < date/time of $AnotherDateTimeObject
my $Result = 0;        # if date/time are equal
my $Result = 1;        # if date/time of $DateTimeObject > date/time of $AnotherDateTimeObject

ToTimeZone()#

Converts the date and time of this object to the given time zone.

my $Success = $DateTimeObject->ToTimeZone(
    TimeZone => 'Europe/Berlin',
);

Returns:

$Success = 1;   # success, or false otherwise.

ToOTRSTimeZone()#

Converts the date and time of this object to the data storage time zone.

my $Success = $DateTimeObject->ToOTRSTimeZone();

Returns:

$Success = 1;   # success, or false otherwise.

Validate()#

Checks if given date, time and time zone would result in a valid date.

my $IsValid = $DateTimeObject->Validate(
    Year     => 2016,
    Month    => 1,
    Day      => 22,
    Hour     => 16,
    Minute   => 35,
    Second   => 59,
    TimeZone => 'Europe/Berlin',
);

Returns:

$IsValid = 1;   # if date/time is valid, or false otherwise.

Format()#

Returns the date/time as string formatted according to format given.

See http://search.cpan.org/~drolsky/DateTime-1.21/lib/DateTime.pm#strftime_Patterns for supported formats.

Short overview of essential formatting options:

%Y or %{year}: four digit year

%m: month with leading zero
%{month}: month without leading zero

%d: day of month with leading zero
%{day}: day of month without leading zero

%H: 24 hour with leading zero
%{hour}: 24 hour without leading zero

%l: 12 hour with leading zero
%{hour_12}: 12 hour without leading zero

%M: minute with leading zero
%{minute}: minute without leading zero

%S: second with leading zero
%{second}: second without leading zero

%{time_zone_long_name}: Time zone, e. g. 'Europe/Berlin'

%{epoch}: Seconds since the epoch (OS specific)
%{offset}: Offset in seconds to GMT/UTC

my $DateTimeString = $DateTimeObject->Format( Format => '%Y-%m-%d %H:%M:%S' );

Returns:

my $String = '2016-01-22 18:07:23';

ToEpoch()#

Returns date/time as seconds since the epoch.

my $Epoch = $DateTimeObject->ToEpoch();

Returns e. g.:

my $Epoch = 1454420017;

ToString()#

Returns date/time as string.

my $DateTimeString = $DateTimeObject->ToString();

Returns e. g.:

$DateTimeString = '2016-01-31 14:05:45'

ToEmailTimeStamp()#

Returns the date/time of this object as time stamp in RFC 2822 format to be used in email headers.

my $MailTimeStamp = $DateTimeObject->ToEmailTimeStamp();

# Typical usage:
# You want to have the date/time of OTRS + its UTC offset, so:
my $DateTimeObject = $Kernel::OM->Create('Kernel::System::DateTime');
my $MailTimeStamp = $DateTimeObject->ToEmailTimeStamp();

# If you already have a DateTime object, possibly in another time zone:
$DateTimeObject->ToOTRSTimeZone();
my $MailTimeStamp = $DateTimeObject->ToEmailTimeStamp();

Returns:

my $String = 'Wed, 2 Sep 2014 16:30:57 +0200';

ToCTimeString()#

Returns date and time as ctime string, as for example returned by Perl’s localtime and gmtime in scalar context.

my $CTimeString = $DateTimeObject->ToCTimeString();

Returns:

my $String = 'Fri Feb 19 16:07:31 2016';

IsVacationDay()#

Checks if date/time of this object is a vacation day.

my $IsVacationDay = $DateTimeObject->IsVacationDay(
    Calendar => 9, # optional, OTRS vacation days otherwise
);

Returns:

my $IsVacationDay = 'some vacation day',    # description of vacation day or 0 if no vacation day.

LastDayOfMonthGet()#

Returns the last day of the month.

$LastDayOfMonth = $DateTimeObject->LastDayOfMonthGet();

Returns:

my $LastDayOfMonth = {
    Day       => 31,
    DayOfWeek => 5,
    DayAbbr   => 'Fri',
};

Clone()#

Clones the DateTime object.

my $ClonedDateTimeObject = $DateTimeObject->Clone();

TimeZoneList()#

Returns an array ref of available time zones.

my $TimeZones = $DateTimeObject->TimeZoneList();

# You can add an obsolete time zone to the list if the time zone is valid.
# This is useful to keep the obsolete time zone from a stored setting
# so that it will e.g. be shown as selected when showing a selection list.
# Otherwise the user would have to select a new time zone.

my $TimeZones = $DateTimeObject->TimeZoneList(
    # Africa/Kinshasa has become obsolete and has been replaced by Africa/Lagos.
    # This option will add Africa/Kinshasa to the list of time zones nonetheless.
    # The given time zone must be valid, so 'Some/InvalidTimeZone' will not be added.
    IncludeTimeZone => 'Africa/Kinshasa',
);

You can also call this function without an object:

my $TimeZones = Kernel::System::DateTime->TimeZoneList();

Returns:

my $TimeZoneList = [
    # ...
    'Europe/Amsterdam',
    'Europe/Andorra',
    'Europe/Athens',
    # ...
];

TimeZoneByOffsetList()#

Returns a list of time zones by offset in hours. Of course, the resulting list depends on the date/time set within this DateTime object.

my %TimeZoneByOffset = $DateTimeObject->TimeZoneByOffsetList();

Returns:

my $TimeZoneByOffsetList = {
    # ...
    -9 => [ 'America/Adak', 'Pacific/Gambier', ],
    # ...
    2  => [
        # ...
        'Europe/Berlin',
        # ...
    ],
    # ...
    8.75 => [ 'Australia/Eucla', ],
    # ...
};

IsTimeZoneValid()#

Checks if the given time zone is valid.

my $Valid = $DateTimeObject->IsTimeZoneValid( TimeZone => 'Europe/Berlin' );

# You can also call this function without an object:
my $Valid = Kernel::System::DateTime->IsTimeZoneValid( TimeZone => 'Europe/Berlin' );
Returns:

$Valid = 1; # if given time zone is valid, 0 otherwise.

GetRealTimeZone()#

Returns the real time zone for the given one. Some time zones become obsolete/invalid over time but must still be mapped to the current/valid ones. DateTime::TimeZone calls this “linked” time zones. For current/valid time zones this function just returns the given time zone.

my $TimeZone = $DateTimeObject->GetRealTimeZone( TimeZone => 'Africa/Addis_Ababa' );

# You can also call this function without an object:
my $TimeZone = Kernel::System::DateTime->GetRealTimeZone( TimeZone => 'Africa/Addis_Ababa' );
Returns:

my $TimeZone = ‘Africa/Nairobi’;

OTRSTimeZoneGet()#

Returns the time zone set for OTRS.

my $OTRSTimeZone = $DateTimeObject->OTRSTimeZoneGet();

# You can also call this function without an object:
my $OTRSTimeZone = Kernel::System::DateTime->OTRSTimeZoneGet();

Returns:

my $OTRSTimeZone = 'Europe/Berlin';

UserDefaultTimeZoneGet()#

Returns the time zone set as default in SysConfig UserDefaultTimeZone for newly created users or existing users without time zone setting.

my $UserDefaultTimeZoneGet = $DateTimeObject->UserDefaultTimeZoneGet();

You can also call this function without an object:

my $UserDefaultTimeZoneGet = Kernel::System::DateTime->UserDefaultTimeZoneGet();

Returns:

my $UserDefaultTimeZone = 'Europe/Berlin';

SystemTimeZoneGet()#

Returns the time zone of the system.

my $SystemTimeZone = $DateTimeObject->SystemTimeZoneGet();

You can also call this function without an object:

my $SystemTimeZone = Kernel::System::DateTime->SystemTimeZoneGet();

Returns:

my $SystemTimeZone = 'Europe/Berlin';

_ToCPANDateTimeParamNames()#

Maps date/time parameter names expected by the functions of this package to the ones expected by CPAN/Perl DateTime package.

my $DateTimeParams = $DateTimeObject->_ToCPANDateTimeParamNames(
    Year     => 2016,
    Month    => 1,
    Day      => 22,
    Hour     => 17,
    Minute   => 20,
    Second   => 2,
    TimeZone => 'Europe/Berlin',
);

Returns:

my $CPANDateTimeParamNames = {
    year      => 2016,
    month     => 1,
    day       => 22,
    hour      => 17,
    minute    => 20,
    second    => 2,
    time_zone => 'Europe/Berlin',
};

_StringToHash()#

Parses a date/time string and returns a hash ref.

my $DateTimeHash = $DateTimeObject->_StringToHash( String => '2016-08-14 22:45:00' );

# Sets second to 0:
my $DateTimeHash = $DateTimeObject->_StringToHash( String => '2016-08-14 22:45' );

# Sets hour, minute and second to 0:
my $DateTimeHash = $DateTimeObject->_StringToHash( String => '2016-08-14' );

# Format with time zone
my $DateTimeHash = $DateTimeObject->_StringToHash(
    String   => '2023-02-17T11:00:00+03:00'
    TimeZone => 'Europe/Berlin', # desired time zone of the created DateTime object, optional
);

Please see C<L</new()>> for the list of supported string formats.

Returns:

my $DateTimeHash = {
    Year   => 2016,
    Month  => 8,
    Day    => 14,
    Hour   => 22,
    Minute => 45,
    Second => 0,
};

_CPANDateTimeObjectCreate()#

Creates a CPAN DateTime object which will be stored within this object and used for date/time calculations.

# Create an object with current date and time
# within time zone set in SysConfig OTRSTimeZone:
my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate();

# Create an object with current date and time
# within a certain time zone:
my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
    TimeZone => 'Europe/Berlin',
);

# Create an object with a specific date and time:
my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
    Year     => 2016,
    Month    => 1,
    Day      => 22,
    Hour     => 12,                 # optional, defaults to 0
    Minute   => 35,                 # optional, defaults to 0
    Second   => 59,                 # optional, defaults to 0
    TimeZone => 'Europe/Berlin',    # optional, defaults to setting of SysConfig OTRSTimeZone
);

# Create an object from an epoch timestamp. These timestamps are always UTC/GMT,
# hence time zone will automatically be set to UTC.
#
# If parameter Epoch is present, all other parameters except TimeZone will be ignored.
my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
    Epoch => 1453911685,
);

# Create an object from a date/time string.
#
# If parameter String is given, Year, Month, Day, Hour, Minute and Second will be ignored. Please see C<L</new()>>
# for the list of supported string formats.
my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
    String   => '2016-08-14 22:45:00',
    TimeZone => 'Europe/Berlin',        # optional, defaults to setting of SysConfig OTRSTimeZone
);

_AutocorrectNonExistingDateTimeForTimeZone()#

Certain times do not exist at certain dates in certain time zones, e.g. 2:00 AM on the day of the DST switch from winter to summer time in time zone Europe/Berlin (1:59 AM switches to 3:00 AM).

In these cases, this function tries to add an hour or a few to get a valid date/time.

my $AutocorrectedCPANDateTimeObject = $DateTimeObject->_AutocorrectNonExistingDateTimeForTimeZone(
    CPANDateTimeObject  => $CPANDateTimeObject, # must be in time zone 'floating'
    DestinationTimeZone => 'Europe/Berlin',
);

Returns a new CPAN DateTime object with the autocorrected time on success.
Note that it's possible that also the day changes, not only the hour.

_OpIsNewerThan()#

Operator overloading for >

_OpIsOlderThan()#

Operator overloading for <

_OpIsNewerThanOrEquals()#

Operator overloading for >=

_OpIsOlderThanOrEquals()#

Operator overloading for <=

_OpEquals()#

Operator overloading for ==

_OpNotEquals()#

Operator overloading for !=