Kernel::System::DateTime

NAME

Kernel::System::DateTime – Handles date and time calculations

DESCRIPTION

Handles date and time calculations.

METHODS

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

Beware! Creating a datetime object with a time zone with daylight saving time (DST) in DST toggle range, is invalid.

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 method "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 methods 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
    };

Note that this method will prefer to use Time::Moment (for faster calculations) if it is installed.

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:

    $Result = -1;       # if date/time of this object < date/time of given object
    $Result = 0;        # if date/time are equal
    $Result = 1:        # if date/time of this object > date/time of given object

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 undef 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 undef 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 also call this method 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' );

Returns: $ValidID = 1; # if given time zone is valid, 0 otherwise.

OTRSTimeZoneGet()

Returns the time zone set for OTRS.

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

    # You can also call this method 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 method 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 method without an object:

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

Returns:

    my $SystemTimeZone = 'Europe/Berlin';
Scroll to Top