Line data Source code
1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /*
3 : * This file is part of the LibreOffice project.
4 : *
5 : * This Source Code Form is subject to the terms of the Mozilla Public
6 : * License, v. 2.0. If a copy of the MPL was not distributed with this
7 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 : *
9 : * This file incorporates work covered by the following license notice:
10 : *
11 : * Licensed to the Apache Software Foundation (ASF) under one or more
12 : * contributor license agreements. See the NOTICE file distributed
13 : * with this work for additional information regarding copyright
14 : * ownership. The ASF licenses this file to you under the Apache
15 : * License, Version 2.0 (the "License"); you may not use this file
16 : * except in compliance with the License. You may obtain a copy of
17 : * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 : */
19 :
20 : #include <unotools/datetime.hxx>
21 : #include <tools/date.hxx>
22 : #include <tools/time.hxx>
23 : #include <tools/datetime.hxx>
24 : #include <stdexcept>
25 : #include <rtl/ustrbuf.hxx>
26 : #include <rtl/math.hxx>
27 :
28 : namespace
29 : {
30 0 : sal_Int32 impl_pow(sal_Int32 x, sal_Int32 y)
31 : {
32 0 : if (y == 1)
33 0 : return x;
34 0 : if ( y % 2 == 0)
35 : {
36 0 : return impl_pow(x*x, y/2);
37 : }
38 : else
39 : {
40 0 : return x * impl_pow(x*x, y/2);
41 : }
42 : }
43 : // computes x^y
44 0 : sal_Int32 pow(sal_Int32 x, sal_Int32 y)
45 : {
46 0 : if (y < 0)
47 0 : throw std::invalid_argument("negative power is not defined in integers");
48 0 : if (y == 0)
49 0 : return 1;
50 0 : return impl_pow(x, y);
51 : }
52 :
53 : /** convert string to number with optional min and max values */
54 : template <typename T>
55 0 : bool convertNumber( T& rValue,
56 : const OUString& rString,
57 : T /*nMin*/ = -1, T /*nMax*/ = -1)
58 : {
59 0 : sal_Bool bNeg = sal_False;
60 0 : rValue = 0;
61 :
62 0 : sal_Int32 nPos = 0L;
63 0 : sal_Int32 nLen = rString.getLength();
64 :
65 : // skip white space
66 0 : while( nPos < nLen && sal_Unicode(' ') == rString[nPos] )
67 0 : nPos++;
68 :
69 0 : if( nPos < nLen && sal_Unicode('-') == rString[nPos] )
70 : {
71 0 : bNeg = sal_True;
72 0 : nPos++;
73 : }
74 :
75 : // get number
76 0 : while( nPos < nLen &&
77 0 : sal_Unicode('0') <= rString[nPos] &&
78 0 : sal_Unicode('9') >= rString[nPos] )
79 : {
80 : // TODO: check overflow!
81 0 : rValue *= 10;
82 0 : rValue += (rString[nPos] - sal_Unicode('0'));
83 0 : nPos++;
84 : }
85 :
86 0 : if( bNeg )
87 0 : rValue *= -1;
88 :
89 0 : return nPos == nLen;
90 : }
91 :
92 : // although the standard calls for fixed-length (zero-padded) tokens
93 : // (in their integer part), we are here liberal and allow shorter tokens
94 : // (when there are separators, else it is ambiguous).
95 : // Note that:
96 : // the token separator is OPTIONAL
97 : // empty string is a valid token! (to recognise hh or hhmm or hh:mm formats)
98 : // returns: success / failure
99 : // in case of failure, no reference argument is changed
100 : // arguments:
101 : // i_str: string to extract token from
102 : // index: index in i_str where to start tokenizing
103 : // after return, start of *next* token (if any)
104 : // if this was the last token, then the value is UNDEFINED
105 : // o_strInt: output; integer part of token
106 : // o_bFraction: output; was there a fractional part?
107 : // o_strFrac: output; fractional part of token
108 0 : bool impl_getISO8601TimeToken(const OUString &i_str, sal_Int32 &nPos, OUString &resInt, bool &bFraction, OUString &resFrac)
109 : {
110 0 : bFraction = false;
111 : // all tokens are of length 2
112 0 : const sal_Int32 nEndPos = nPos + 2;
113 0 : const sal_Unicode c0 = '0';
114 0 : const sal_Unicode c9 = '9';
115 0 : const sal_Unicode sep = ':';
116 0 : for (;nPos < nEndPos && nPos < i_str.getLength(); ++nPos)
117 : {
118 0 : const sal_Unicode c = i_str[nPos];
119 0 : if (c == sep)
120 0 : return true;
121 0 : if (c < c0 || c > c9)
122 0 : return false;
123 0 : resInt += OUString(c);
124 : }
125 0 : if (nPos == i_str.getLength() || i_str[nPos] == sep)
126 0 : return true;
127 0 : if (i_str[nPos] == ',' || i_str[nPos] == '.')
128 : {
129 0 : bFraction = true;
130 0 : ++nPos;
131 0 : for (; nPos < i_str.getLength(); ++nPos)
132 : {
133 0 : const sal_Unicode c = i_str[nPos];
134 0 : if (c == sep)
135 : // fractional part allowed only in *last* token
136 0 : return false;
137 0 : if (c < c0 || c > c9)
138 0 : return false;
139 0 : resFrac += OUString(c);
140 : }
141 : OSL_ENSURE(nPos == i_str.getLength(), "impl_getISO8601TimeToken internal error; expected to be at end of string");
142 0 : return true;
143 : }
144 : else
145 0 : return false;
146 : }
147 0 : inline bool getISO8601TimeToken(const OUString &i_str, sal_Int32 &io_index, OUString &o_strInt, bool &o_bFraction, OUString &o_strFrac)
148 : {
149 0 : OUString resInt;
150 0 : OUString resFrac;
151 0 : bool bFraction = false;
152 0 : sal_Int32 index = io_index;
153 0 : if(!impl_getISO8601TimeToken(i_str, index, resInt, bFraction, resFrac))
154 0 : return false;
155 : else
156 : {
157 0 : io_index = index+1;
158 0 : o_strInt = resInt;
159 0 : o_strFrac = resFrac;
160 0 : o_bFraction = bFraction;
161 0 : return true;
162 0 : }
163 : }
164 : }
165 :
166 : //.........................................................................
167 : namespace utl
168 : {
169 : //------------------------------------------------------------------
170 0 : void typeConvert(const Date& _rDate, starutil::Date& _rOut)
171 : {
172 0 : _rOut.Day = _rDate.GetDay();
173 0 : _rOut.Month = _rDate.GetMonth();
174 0 : _rOut.Year = _rDate.GetYear();
175 0 : }
176 :
177 : //------------------------------------------------------------------
178 0 : void typeConvert(const starutil::Date& _rDate, Date& _rOut)
179 : {
180 0 : _rOut = Date(_rDate.Day, _rDate.Month, _rDate.Year);
181 0 : }
182 :
183 : //------------------------------------------------------------------
184 0 : void typeConvert(const DateTime& _rDateTime, starutil::DateTime& _rOut)
185 : {
186 0 : _rOut.Year = _rDateTime.GetYear();
187 0 : _rOut.Month = _rDateTime.GetMonth();
188 0 : _rOut.Day = _rDateTime.GetDay();
189 0 : _rOut.Hours = _rDateTime.GetHour();
190 0 : _rOut.Minutes = _rDateTime.GetMin();
191 0 : _rOut.Seconds = _rDateTime.GetSec();
192 0 : _rOut.NanoSeconds = _rDateTime.GetNanoSec();
193 0 : }
194 :
195 : //------------------------------------------------------------------
196 0 : void typeConvert(const starutil::DateTime& _rDateTime, DateTime& _rOut)
197 : {
198 0 : Date aDate(_rDateTime.Day, _rDateTime.Month, _rDateTime.Year);
199 0 : Time aTime(_rDateTime.Hours, _rDateTime.Minutes, _rDateTime.Seconds, _rDateTime.NanoSeconds);
200 0 : _rOut = DateTime(aDate, aTime);
201 0 : }
202 :
203 :
204 0 : OUString toISO8601(const starutil::DateTime& rDateTime)
205 : {
206 0 : OUStringBuffer rBuffer;
207 0 : rBuffer.append((sal_Int32) rDateTime.Year);
208 0 : rBuffer.append('-');
209 0 : if( rDateTime.Month < 10 )
210 0 : rBuffer.append('0');
211 0 : rBuffer.append((sal_Int32) rDateTime.Month);
212 0 : rBuffer.append('-');
213 0 : if( rDateTime.Day < 10 )
214 0 : rBuffer.append('0');
215 0 : rBuffer.append((sal_Int32) rDateTime.Day);
216 :
217 0 : if( rDateTime.NanoSeconds != 0 ||
218 0 : rDateTime.Seconds != 0 ||
219 0 : rDateTime.Minutes != 0 ||
220 0 : rDateTime.Hours != 0 )
221 : {
222 0 : rBuffer.append('T');
223 0 : if( rDateTime.Hours < 10 )
224 0 : rBuffer.append('0');
225 0 : rBuffer.append((sal_Int32) rDateTime.Hours);
226 0 : rBuffer.append(':');
227 0 : if( rDateTime.Minutes < 10 )
228 0 : rBuffer.append('0');
229 0 : rBuffer.append((sal_Int32) rDateTime.Minutes);
230 0 : rBuffer.append(':');
231 0 : if( rDateTime.Seconds < 10 )
232 0 : rBuffer.append('0');
233 0 : rBuffer.append((sal_Int32) rDateTime.Seconds);
234 0 : if ( rDateTime.NanoSeconds > 0)
235 : {
236 : OSL_ENSURE(rDateTime.NanoSeconds < 1000000000,"NanoSeconds cannot be more than 999 999 999");
237 0 : rBuffer.append(',');
238 0 : std::ostringstream ostr;
239 0 : ostr.fill('0');
240 0 : ostr.width(9);
241 0 : ostr << rDateTime.NanoSeconds;
242 0 : rBuffer.append(OUString::createFromAscii(ostr.str().c_str()));
243 : }
244 : }
245 0 : return rBuffer.makeStringAndClear();
246 : }
247 :
248 0 : OUString toISO8601(const starutil::Time& rTime)
249 : {
250 0 : OUStringBuffer rBuffer;
251 0 : if( rTime.Hours < 10 )
252 0 : rBuffer.append('0');
253 0 : rBuffer.append((sal_Int32) rTime.Hours);
254 0 : rBuffer.append(':');
255 0 : if( rTime.Minutes < 10 )
256 0 : rBuffer.append('0');
257 0 : rBuffer.append((sal_Int32) rTime.Minutes);
258 0 : rBuffer.append(':');
259 0 : if( rTime.Seconds < 10 )
260 0 : rBuffer.append('0');
261 0 : rBuffer.append((sal_Int32) rTime.Seconds);
262 0 : if ( rTime.NanoSeconds > 0)
263 : {
264 : OSL_ENSURE(rTime.NanoSeconds < 1000000000,"NanoSeconds cannot be more than 999 999 999");
265 0 : rBuffer.append(',');
266 0 : std::ostringstream ostr;
267 0 : ostr.fill('0');
268 0 : ostr.width(9);
269 0 : ostr << rTime.NanoSeconds;
270 0 : rBuffer.append(OUString::createFromAscii(ostr.str().c_str()));
271 : }
272 0 : return rBuffer.makeStringAndClear();
273 : }
274 :
275 : /** convert ISO8601 DateTime String to util::DateTime */
276 0 : bool ISO8601parseDateTime(const OUString &rString, starutil::DateTime& rDateTime)
277 : {
278 0 : bool bSuccess = true;
279 :
280 0 : rtl::OUString aDateStr, aTimeStr;
281 0 : starutil::Date aDate;
282 0 : starutil::Time aTime;
283 0 : sal_Int32 nPos = rString.indexOf( (sal_Unicode) 'T' );
284 0 : if ( nPos >= 0 )
285 : {
286 0 : aDateStr = rString.copy( 0, nPos );
287 0 : aTimeStr = rString.copy( nPos + 1 );
288 : }
289 : else
290 0 : aDateStr = rString; // no separator: only date part
291 :
292 0 : bSuccess = ISO8601parseDate(aDateStr, aDate);
293 :
294 0 : if ( bSuccess && !aTimeStr.isEmpty() ) // time is optional
295 : {
296 0 : bSuccess = ISO8601parseTime(aTimeStr, aTime);
297 : }
298 :
299 0 : if (bSuccess)
300 : {
301 : rDateTime = starutil::DateTime(aTime.NanoSeconds, aTime.Seconds, aTime.Minutes, aTime.Hours,
302 0 : aDate.Day, aDate.Month, aDate.Year);
303 : }
304 :
305 0 : return bSuccess;
306 : }
307 :
308 : /** convert ISO8601 Date String to util::Date */
309 : // TODO: supports only calendar dates YYYY-MM-DD
310 : // MISSING: calendar dates YYYYMMDD YYYY-MM
311 : // year, week date, ordinal date
312 0 : bool ISO8601parseDate(const OUString &aDateStr, starutil::Date& rDate)
313 : {
314 0 : bool bSuccess = true;
315 :
316 0 : sal_Int32 nYear = 1899;
317 0 : sal_Int32 nMonth = 12;
318 0 : sal_Int32 nDay = 30;
319 :
320 0 : const sal_Unicode* pStr = aDateStr.getStr();
321 0 : sal_Int32 nDateTokens = 1;
322 0 : while ( *pStr )
323 : {
324 0 : if ( *pStr == '-' )
325 0 : nDateTokens++;
326 0 : pStr++;
327 : }
328 0 : if ( nDateTokens > 3 || aDateStr.isEmpty() )
329 0 : bSuccess = false;
330 : else
331 : {
332 0 : sal_Int32 n = 0;
333 0 : if ( !convertNumber<sal_Int32>( nYear, aDateStr.getToken( 0, '-', n ), 0, 9999 ) )
334 0 : bSuccess = false;
335 0 : if ( nDateTokens >= 2 )
336 0 : if ( !convertNumber<sal_Int32>( nMonth, aDateStr.getToken( 0, '-', n ), 0, 12 ) )
337 0 : bSuccess = false;
338 0 : if ( nDateTokens >= 3 )
339 0 : if ( !convertNumber<sal_Int32>( nDay, aDateStr.getToken( 0, '-', n ), 0, 31 ) )
340 0 : bSuccess = false;
341 : }
342 :
343 0 : if (bSuccess)
344 : {
345 0 : rDate.Year = (sal_uInt16)nYear;
346 0 : rDate.Month = (sal_uInt16)nMonth;
347 0 : rDate.Day = (sal_uInt16)nDay;
348 : }
349 :
350 0 : return bSuccess;
351 : }
352 :
353 : /** convert ISO8601 Time String to util::Time */
354 0 : bool ISO8601parseTime(const OUString &aTimeStr, starutil::Time& rTime)
355 : {
356 0 : bool bSuccess = true;
357 :
358 0 : sal_Int32 nHour = 0;
359 0 : sal_Int32 nMin = 0;
360 0 : sal_Int32 nSec = 0;
361 0 : sal_Int32 nNanoSec = 0;
362 :
363 0 : sal_Int32 n = 0;
364 0 : OUString tokInt;
365 0 : OUString tokFrac;
366 0 : bool bFrac = false;
367 : // hours
368 0 : if (bSuccess && (bSuccess = getISO8601TimeToken(aTimeStr, n, tokInt, bFrac, tokFrac)))
369 : {
370 0 : if ( bFrac && n < aTimeStr.getLength())
371 : // junk after ISO time
372 0 : bSuccess = false;
373 0 : else if ( (bSuccess = convertNumber<sal_Int32>( nHour, tokInt, 0, 23 )) )
374 : {
375 0 : if (bFrac)
376 : {
377 : sal_Int64 fracNumerator;
378 0 : if ( (bSuccess = convertNumber(fracNumerator, tokFrac)) )
379 : {
380 0 : double frac = static_cast<double>(fracNumerator) / static_cast<double>(pow(10, tokFrac.getLength()));
381 : // minutes
382 : OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac hours (of hours) not between 0 and 1");
383 0 : frac *= 60;
384 0 : nMin = floor(frac);
385 0 : frac -= nMin;
386 : // seconds
387 : OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac minutes (of hours) not between 0 and 1");
388 0 : frac *= 60;
389 0 : nSec = floor(frac);
390 0 : frac -= nSec;
391 : // nanoseconds
392 : OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac seconds (of hours) not between 0 and 1");
393 0 : frac *= 1000000000;
394 0 : nNanoSec = ::rtl::math::round(frac);
395 : }
396 0 : goto end;
397 : }
398 0 : if(n >= aTimeStr.getLength())
399 0 : goto end;
400 : }
401 : }
402 :
403 : // minutes
404 0 : if (bSuccess && (bSuccess = getISO8601TimeToken(aTimeStr, n, tokInt, bFrac, tokFrac)))
405 : {
406 0 : if ( bFrac && n < aTimeStr.getLength())
407 : // junk after ISO time
408 0 : bSuccess = false;
409 0 : else if ( (bSuccess = convertNumber<sal_Int32>( nMin, tokInt, 0, 59 )) )
410 : {
411 0 : if (bFrac)
412 : {
413 : sal_Int64 fracNumerator;
414 0 : if ( (bSuccess = convertNumber(fracNumerator, tokFrac)) )
415 : {
416 0 : double frac = static_cast<double>(fracNumerator) / static_cast<double>(pow(10, tokFrac.getLength()));
417 : // seconds
418 : OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac minutes (of minutes) not between 0 and 1");
419 0 : frac *= 60;
420 0 : nSec = floor(frac);
421 0 : frac -= nSec;
422 : // nanoseconds
423 : OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac seconds (of minutes) not between 0 and 1");
424 0 : frac *= 1000000000;
425 0 : nNanoSec = ::rtl::math::round(frac);
426 : }
427 0 : goto end;
428 : }
429 0 : if(n >= aTimeStr.getLength())
430 0 : goto end;
431 : }
432 : }
433 : // seconds
434 0 : if (bSuccess && (bSuccess = getISO8601TimeToken(aTimeStr, n, tokInt, bFrac, tokFrac)))
435 : {
436 0 : if (n < aTimeStr.getLength())
437 : // junk after ISO time
438 0 : bSuccess = false;
439 : // max 60 for leap seconds
440 0 : else if ( (bSuccess = convertNumber<sal_Int32>( nSec, tokInt, 0, 60 )) )
441 : {
442 0 : if (bFrac)
443 : {
444 : sal_Int64 fracNumerator;
445 0 : if ( (bSuccess = convertNumber(fracNumerator, tokFrac)) )
446 : {
447 0 : double frac = static_cast<double>(fracNumerator) / static_cast<double>(pow(10, tokFrac.getLength()));
448 : // nanoseconds
449 : OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac seconds (of seconds) not between 0 and 1");
450 0 : frac *= 1000000000;
451 0 : nNanoSec = ::rtl::math::round(frac);
452 : }
453 0 : goto end;
454 : }
455 : }
456 : }
457 :
458 : end:
459 0 : if (bSuccess)
460 : {
461 : // normalise time
462 0 : const int secondsOverFlow = (nSec == 60) ? 61 : 60;
463 0 : if (nNanoSec == 1000000000)
464 : {
465 0 : nNanoSec = 0;
466 0 : ++nSec;
467 : }
468 0 : if(nSec == secondsOverFlow)
469 : {
470 0 : nSec = 0;
471 0 : ++nMin;
472 : }
473 0 : if(nMin == 60)
474 : {
475 0 : nMin = 0;
476 0 : ++nHour;
477 : }
478 :
479 0 : rTime.Hours = (sal_uInt16)nHour;
480 0 : rTime.Minutes = (sal_uInt16)nMin;
481 0 : rTime.Seconds = (sal_uInt16)nSec;
482 0 : rTime.NanoSeconds = nNanoSec;
483 : }
484 :
485 0 : return bSuccess;
486 : }
487 : //.........................................................................
488 : } // namespace utl
489 : //.........................................................................
490 :
491 : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|