lib

IsoDuration.h
1/* This file is part of the KDE project
2 Copyright (C) 2005 David Faure <faure@kde.org>
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License version 2 as published by the Free Software Foundation.
7
8 This library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details.
12
13 You should have received a copy of the GNU Library General Public License
14 along with this library; see the file COPYING.LIB. If not, write to
15 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16 * Boston, MA 02110-1301, USA.
17*/
18
19#include <tqstring.h>
20
30static TQString minutesToISODuration( int mn )
31{
32 bool neg = mn < 0;
33 // PT == period of time - see ISO8601
34 TQString str = TQString::fromLatin1( "PT00H%1M00S" ).arg( TQABS( mn ) );
35 if ( neg )
36 str.prepend( '-' );
37 return str;
38}
39
40static TQString daysToISODuration( int days )
41{
42 bool neg = days < 0;
43 // P == period, time is ommitted - see ISO8601
44 TQString str = TQString::fromLatin1( "P%1D" ).arg( TQABS( days ) );
45 if ( neg )
46 str.prepend( '-' );
47 return str;
48}
49
50static int ISODurationToMinutes( const TQString& str )
51{
52 int idx = 0;
53 const int len = str.length();
54 bool neg = str[idx] == '-';
55 if ( neg )
56 ++idx;
57 if ( idx < len && str[idx] == 'P' ) // should always be true
58 ++idx;
59 if ( idx < len && str[idx] == 'T' )
60 ++idx;
61 int minutes = 0;
62 int currentNum = 0;
63 while ( idx < len ) {
64 if ( str[idx].isDigit() )
65 currentNum = currentNum * 10 + str[idx].latin1() - '0';
66 else {
67 if ( str[idx] == 'D' )
68 minutes += 24 * 60 * currentNum;
69 else if ( str[idx] == 'H' )
70 minutes += 60 * currentNum;
71 else if ( str[idx] == 'M' )
72 minutes += currentNum;
73 currentNum = 0;
74 }
75 ++idx;
76 }
77 return neg ? -minutes : minutes;
78}
79
80static int ISODurationToDays( const TQString& str )
81{
82 int idx = 0;
83 const int len = str.length();
84 bool neg = str[idx] == '-';
85 if ( neg )
86 ++idx;
87 if ( idx < len && str[idx] == 'P' ) // should always be true
88 ++idx;
89 if ( idx < len && str[idx] == 'T' )
90 ++idx;
91 int days = 0;
92 int currentNum = 0;
93 while ( idx < len ) {
94 if ( str[idx].isDigit() )
95 currentNum = currentNum * 10 + str[idx].latin1() - '0';
96 else {
97 if ( str[idx] == 'Y' )
98 days += 365 * currentNum;
99 else if ( str[idx] == 'M' )
100 days += 30 * currentNum; // approx
101 else if ( str[idx] == 'D' )
102 days += currentNum;
103 currentNum = 0;
104 }
105 ++idx;
106 }
107 return neg ? -days : days;
108}
109