Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / SL / Helper / DateTime.pm
1 package DateTime;
2
3 use strict;
4
5 use SL::Util qw(_hashify);
6
7 sub now_local {
8   return shift->now(time_zone => $::locale->get_local_time_zone);
9 }
10
11 sub today_local {
12   return shift->now(time_zone => $::locale->get_local_time_zone)->truncate(to => 'day');
13 }
14
15 sub to_kivitendo_time {
16   my ($self, %params) = _hashify(1, @_);
17   return $::locale->format_date_object_to_time($self, %params);
18 }
19
20 sub to_kivitendo {
21   my ($self, %params) = _hashify(1, @_);
22   return $::locale->format_date_object($self, %params);
23 }
24
25 sub to_lxoffice {
26   # Legacy name.
27   goto &to_kivitendo;
28 }
29
30 sub from_kivitendo {
31   return $::locale->parse_date_to_object($_[1]);
32 }
33
34 sub from_lxoffice {
35   # Legacy name.
36   goto &from_kivitendo;
37 }
38
39 sub add_business_duration {
40   my ($self, %params) = @_;
41
42   my $abs_days = abs $params{days};
43   my $neg      = $params{days} < 0;
44   my $bweek    = $params{businessweek} || 5;
45   my $weeks    = int ($abs_days / $bweek);
46   my $days     = $abs_days % $bweek;
47
48   if ($neg) {
49     $self->subtract(weeks => $weeks);
50     $self->add(days => 8 - $self->day_of_week) if $self->day_of_week > $bweek;
51     $self->subtract(days => $self->day_of_week > $days ? $days : $days + (7 - $bweek));
52   } else {
53     $self->add(weeks => $weeks);
54     $self->subtract(days => $self->day_of_week - $bweek) if $self->day_of_week > $bweek;
55     $self->add(days => $self->day_of_week + $days <= $bweek ? $days : $days + (7 - $bweek));
56   }
57
58   $self;
59 }
60
61 sub add_businessdays {
62   my ($self, %params) = @_;
63
64   $self->add_business_duration(%params);
65 }
66
67 sub subtract_businessdays {
68   my ($self, %params) = @_;
69
70   $params{days} *= -1;
71
72   $self->add_business_duration(%params);
73 }
74
75 1;
76
77 __END__
78
79 =encoding utf8
80
81 =head1 NAME
82
83 SL::Helpers::DateTime - helper functions for L<DateTime>
84
85 =head1 FUNCTIONS
86
87 =over 4
88
89 =item C<now_local>
90
91 Returns the current time with the time zone set to the local time zone.
92
93 =item C<today_local>
94
95 Returns the current date with the time zone set to the local time zone.
96
97 =item C<to_kivitendo %param>
98
99 Formats the date and time according to the current kivitendo user's
100 date format with L<Locale::format_datetime_object>.
101
102 The legacy name C<to_lxoffice> is still supported.
103
104 =item C<from_kivitendo $string>
105
106 Parses a date string formatted in the current kivitendo user's date
107 format and returns an instance of L<DateTime>.
108
109 Note that only dates can be parsed at the moment, not the time
110 component (as opposed to L<to_kivitendo>).
111
112 The legacy name C<from_lxoffice> is still supported.
113
114 =back
115
116 =head1 AUTHOR
117
118 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
119
120 =cut