LibreOffice Module unotools (master) 1
datetime.cxx
Go to the documentation of this file.
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>
23#include <tools/date.hxx>
24#include <tools/time.hxx>
25#include <tools/datetime.hxx>
26#include <rtl/ustrbuf.hxx>
27#include <rtl/math.hxx>
28#include <osl/diagnose.h>
29#include <comphelper/string.hxx>
30#include <o3tl/string_view.hxx>
31#include <cstddef>
32#include <sstream>
33
34namespace
35{
36 bool checkAllNumber(std::u16string_view rString)
37 {
38 sal_Int32 nPos = 0;
39 sal_Int32 nLen = rString.size();
40
41 // skip white space
42 while( nPos < nLen && ' ' == rString[nPos] )
43 nPos++;
44
45 if( nPos < nLen && '-' == rString[nPos] )
46 nPos++;
47
48 // get number
49 while( nPos < nLen &&
50 '0' <= rString[nPos] &&
51 '9' >= rString[nPos] )
52 {
53 nPos++;
54 }
55
56 return nPos == nLen;
57 }
58
60 bool convertNumber32(sal_Int32& rValue,
61 std::u16string_view rString,
62 sal_Int32 /*nMin*/ = -1, sal_Int32 /*nMax*/ = -1)
63 {
64 if (!checkAllNumber(rString))
65 {
66 rValue = 0;
67 return false;
68 }
69
70 rValue = o3tl::toInt32(rString);
71 return true;
72 }
73
74 bool convertNumber64(sal_Int64& rValue,
75 std::u16string_view rString,
76 sal_Int64 /*nMin*/ = -1, sal_Int64 /*nMax*/ = -1)
77 {
78 if (!checkAllNumber(rString))
79 {
80 rValue = 0;
81 return false;
82 }
83
84 rValue = o3tl::toInt64(rString);
85 return true;
86 }
87
88 // although the standard calls for fixed-length (zero-padded) tokens
89 // (in their integer part), we are here liberal and allow shorter tokens
90 // (when there are separators, else it is ambiguous).
91 // Note that:
92 // the token separator is OPTIONAL
93 // empty string is a valid token! (to recognise hh or hhmm or hh:mm formats)
94 // returns: success / failure
95 // in case of failure, no reference argument is changed
96 // arguments:
97 // i_str: string to extract token from
98 // index: index in i_str where to start tokenizing
99 // after return, start of *next* token (if any)
100 // if this was the last token, then the value is UNDEFINED
101 // o_strInt: output; integer part of token
102 // o_bFraction: output; was there a fractional part?
103 // o_strFrac: output; fractional part of token
104 bool impl_getISO8601TimeToken(std::u16string_view i_str, std::size_t &nPos, OUString &resInt, bool &bFraction, OUString &resFrac)
105 {
106 bFraction = false;
107 // all tokens are of length 2
108 const std::size_t nEndPos = nPos + 2;
109 const sal_Unicode c0 = '0';
110 const sal_Unicode c9 = '9';
111 const sal_Unicode sep = ':';
112 for (;nPos < nEndPos && nPos < i_str.size(); ++nPos)
113 {
114 const sal_Unicode c = i_str[nPos];
115 if (c == sep)
116 return true;
117 if (c < c0 || c > c9)
118 return false;
119 resInt += OUStringChar(c);
120 }
121 if (nPos == 0)
122 return false;
123 if (nPos == i_str.size() || i_str[nPos] == sep)
124 return true;
125 if (i_str[nPos] == ',' || i_str[nPos] == '.')
126 {
127 bFraction = true;
128 ++nPos;
129 for (; nPos < i_str.size(); ++nPos)
130 {
131 const sal_Unicode c = i_str[nPos];
132 if (c == 'Z' || c == '+' || c == '-')
133 {
134 --nPos; // we don't want to skip the tz separator
135 return true;
136 }
137 if (c == sep)
138 // fractional part allowed only in *last* token
139 return false;
140 if (c < c0 || c > c9)
141 return false;
142 resFrac += OUStringChar(c);
143 }
144 OSL_ENSURE(nPos == i_str.size(), "impl_getISO8601TimeToken internal error; expected to be at end of string");
145 return true;
146 }
147 if (i_str[nPos] == 'Z' || i_str[nPos] == '+' || i_str[nPos] == '-')
148 {
149 --nPos; // we don't want to skip the tz separator
150 return true;
151 }
152 else
153 return false;
154 }
155 bool getISO8601TimeToken(std::u16string_view i_str, std::size_t &io_index, OUString &o_strInt, bool &o_bFraction, OUString &o_strFrac)
156 {
157 OUString resInt;
158 OUString resFrac;
159 bool bFraction = false;
160 std::size_t index = io_index;
161 if(!impl_getISO8601TimeToken(i_str, index, resInt, bFraction, resFrac))
162 return false;
163 else
164 {
165 io_index = index+1;
166 o_strInt = resInt;
167 o_strFrac = resFrac;
168 o_bFraction = bFraction;
169 return true;
170 }
171 }
172 bool getISO8601TimeZoneToken(std::u16string_view i_str, std::size_t &io_index, OUString &o_strInt)
173 {
174 const sal_Unicode c0 = '0';
175 const sal_Unicode c9 = '9';
176 const sal_Unicode sep = ':';
177 if (i_str[io_index] == 'Z') // UTC timezone indicator
178 {
179 ++io_index;
180 o_strInt = "Z";
181 return true;
182 }
183 else if (i_str[io_index] == '+' || i_str[io_index] == '-') // other timezones indicator
184 {
185 ++io_index;
186 o_strInt.clear();
187 for (; io_index < i_str.size(); ++io_index)
188 {
189 const sal_Unicode c = i_str[io_index];
190 if ((c < c0 || c > c9) && c != sep)
191 return false;
192 o_strInt += OUStringChar(c);
193 }
194 return true;
195 }
196 else
197 return false;
198 }
199}
200
201namespace utl
202{
204{
205 static SvtSysLocale ourSysLocale;
206 return ourSysLocale.GetLocaleData();
207}
208
209DateTime GetDateTime(const css::util::DateTime& _rDT) { return DateTime(_rDT); }
210
211OUString GetDateTimeString(const css::util::DateTime& _rDT)
212{
213 // String with date and time information (#i20172#)
214 DateTime aDT(GetDateTime(_rDT));
215 const LocaleDataWrapper& rLoDa = GetLocaleData();
216
217 return rLoDa.getDate(aDT) + " " + rLoDa.getTime(aDT);
218}
219
220OUString GetDateTimeString(sal_Int32 _nDate, sal_Int32 _nTime)
221{
222 const LocaleDataWrapper& rLoDa = GetLocaleData();
223
224 Date aDate(_nDate);
226 return rLoDa.getDate(aDate) + ", " + rLoDa.getTime(aTime);
227}
228
229OUString GetDateString(const css::util::DateTime& _rDT)
230{
231 return GetLocaleData().getDate(GetDateTime(_rDT));
232}
233
234void typeConvert(const Date& _rDate, css::util::Date& _rOut)
235{
236 _rOut.Day = _rDate.GetDay();
237 _rOut.Month = _rDate.GetMonth();
238 _rOut.Year = _rDate.GetYear();
239}
240
241void typeConvert(const css::util::Date& _rDate, Date& _rOut)
242{
243 _rOut = Date(_rDate.Day, _rDate.Month, _rDate.Year);
244}
245
246void typeConvert(const DateTime& _rDateTime, css::util::DateTime& _rOut)
247{
248 _rOut.Year = _rDateTime.GetYear();
249 _rOut.Month = _rDateTime.GetMonth();
250 _rOut.Day = _rDateTime.GetDay();
251 _rOut.Hours = _rDateTime.GetHour();
252 _rOut.Minutes = _rDateTime.GetMin();
253 _rOut.Seconds = _rDateTime.GetSec();
254 _rOut.NanoSeconds = _rDateTime.GetNanoSec();
255}
256
257void typeConvert(const css::util::DateTime& _rDateTime, DateTime& _rOut)
258{
259 Date aDate(_rDateTime.Day, _rDateTime.Month, _rDateTime.Year);
260 tools::Time aTime(_rDateTime.Hours, _rDateTime.Minutes, _rDateTime.Seconds, _rDateTime.NanoSeconds);
261 _rOut = DateTime(aDate, aTime);
262}
263
264OUString toISO8601(const css::util::DateTime& rDateTime)
265{
266 OUStringBuffer rBuffer(32);
267 rBuffer.append(OUString::number(static_cast<sal_Int32>(rDateTime.Year)) + "-");
268 if( rDateTime.Month < 10 )
269 rBuffer.append('0');
270 rBuffer.append(OUString::number(static_cast<sal_Int32>(rDateTime.Month)) + "-");
271 if( rDateTime.Day < 10 )
272 rBuffer.append('0');
273 rBuffer.append(static_cast<sal_Int32>(rDateTime.Day));
274
275 if( rDateTime.NanoSeconds != 0 ||
276 rDateTime.Seconds != 0 ||
277 rDateTime.Minutes != 0 ||
278 rDateTime.Hours != 0 )
279 {
280 rBuffer.append('T');
281 if( rDateTime.Hours < 10 )
282 rBuffer.append('0');
283 rBuffer.append(OUString::number(static_cast<sal_Int32>(rDateTime.Hours)) + ":");
284 if( rDateTime.Minutes < 10 )
285 rBuffer.append('0');
286 rBuffer.append(OUString::number(static_cast<sal_Int32>(rDateTime.Minutes)) + ":");
287 if( rDateTime.Seconds < 10 )
288 rBuffer.append('0');
289 rBuffer.append(static_cast<sal_Int32>(rDateTime.Seconds));
290 if ( rDateTime.NanoSeconds > 0)
291 {
292 OSL_ENSURE(rDateTime.NanoSeconds < 1000000000,"NanoSeconds cannot be more than 999 999 999");
293 rBuffer.append(',');
294 std::ostringstream ostr;
295 ostr.fill('0');
296 ostr.width(9);
297 ostr << rDateTime.NanoSeconds;
298 rBuffer.appendAscii(ostr.str().c_str());
299 }
300 }
301 return rBuffer.makeStringAndClear();
302}
303
305bool ISO8601parseDateTime(std::u16string_view rString, css::util::DateTime& rDateTime)
306{
307 bool bSuccess = true;
308
309 std::u16string_view aDateStr, aTimeStr;
310 css::util::Date aDate;
311 css::util::Time aTime;
312 size_t nPos = rString.find( 'T' );
313 if ( nPos != std::u16string_view::npos )
314 {
315 aDateStr = rString.substr( 0, nPos );
316 aTimeStr = rString.substr( nPos + 1 );
317 }
318 else
319 aDateStr = rString; // no separator: only date part
320
321 bSuccess = ISO8601parseDate(aDateStr, aDate);
322
323 if ( bSuccess && !aTimeStr.empty() ) // time is optional
324 {
325 bSuccess = ISO8601parseTime(aTimeStr, aTime);
326 }
327
328 if (bSuccess)
329 {
330 rDateTime = css::util::DateTime(aTime.NanoSeconds, aTime.Seconds, aTime.Minutes, aTime.Hours,
331 aDate.Day, aDate.Month, aDate.Year, false);
332 }
333
334 return bSuccess;
335}
336
338// TODO: supports only calendar dates YYYY-MM-DD
339// MISSING: calendar dates YYYYMMDD YYYY-MM
340// year, week date, ordinal date
341bool ISO8601parseDate(std::u16string_view aDateStr, css::util::Date& rDate)
342{
343 const sal_Int32 nDateTokens {comphelper::string::getTokenCount(aDateStr, '-')};
344
345 if (nDateTokens<1 || nDateTokens>3)
346 return false;
347
348 sal_Int32 nYear = 1899;
349 sal_Int32 nMonth = 12;
350 sal_Int32 nDay = 30;
351
352 sal_Int32 nIdx {0};
353 auto strCurrentToken = o3tl::getToken(aDateStr, 0, '-', nIdx );
354 if ( !convertNumber32( nYear, strCurrentToken, 0, 9999 ) )
355 return false;
356 if ( nDateTokens >= 2 )
357 {
358 strCurrentToken = o3tl::getToken(aDateStr, 0, '-', nIdx );
359 if (strCurrentToken.size() > 2)
360 return false;
361 if ( !convertNumber32( nMonth, strCurrentToken, 0, 12 ) )
362 return false;
363 }
364 if ( nDateTokens >= 3 )
365 {
366 strCurrentToken = o3tl::getToken(aDateStr, 0, '-', nIdx );
367 if (strCurrentToken.size() > 2)
368 return false;
369 if ( !convertNumber32( nDay, strCurrentToken, 0, 31 ) )
370 return false;
371 }
372
373 rDate.Year = static_cast<sal_uInt16>(nYear);
374 rDate.Month = static_cast<sal_uInt16>(nMonth);
375 rDate.Day = static_cast<sal_uInt16>(nDay);
376
377 return true;
378}
379
381bool ISO8601parseTime(std::u16string_view aTimeStr, css::util::Time& rTime)
382{
383 sal_Int32 nHour = 0;
384 sal_Int32 nMin = 0;
385 sal_Int32 nSec = 0;
386 sal_Int32 nNanoSec = 0;
387
388 std::size_t n = 0;
389 OUString tokInt;
390 OUString tokFrac;
391 OUString tokTz;
392 bool bFrac = false;
393 // hours
394 bool bSuccess = getISO8601TimeToken(aTimeStr, n, tokInt, bFrac, tokFrac);
395 if (!bSuccess)
396 return false;
397
398 if ( bFrac && n < aTimeStr.size())
399 {
400 // is it junk or the timezone?
401 bSuccess = getISO8601TimeZoneToken(aTimeStr, n, tokTz);
402 if (!bSuccess)
403 return false;
404 }
405 bSuccess = convertNumber32( nHour, tokInt, 0, 23 );
406 if (!bSuccess)
407 return false;
408
409 if (bFrac)
410 {
411 sal_Int64 fracNumerator;
412 bSuccess = convertNumber64(fracNumerator, tokFrac);
413 if ( bSuccess )
414 {
415 double frac = static_cast<double>(fracNumerator) / pow(static_cast<double>(10), static_cast<double>(tokFrac.getLength()));
416 // minutes
417 OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac hours (of hours) not between 0 and 1");
418 frac *= 60;
419 nMin = floor(frac);
420 frac -= nMin;
421 // seconds
422 OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac minutes (of hours) not between 0 and 1");
423 frac *= 60;
424 nSec = floor(frac);
425 frac -= nSec;
426 // nanoseconds
427 OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac seconds (of hours) not between 0 and 1");
428 frac *= 1000000000;
429 nNanoSec = ::rtl::math::round(frac);
430 }
431 goto end;
432 }
433 if(n >= aTimeStr.size())
434 goto end;
435
436 // minutes
437 bSuccess = getISO8601TimeToken(aTimeStr, n, tokInt, bFrac, tokFrac);
438 if (!bSuccess)
439 return false;
440 if ( bFrac && n < aTimeStr.size())
441 {
442 // is it junk or the timezone?
443 bSuccess = getISO8601TimeZoneToken(aTimeStr, n, tokTz);
444 if (!bSuccess)
445 return false;
446 }
447 bSuccess = convertNumber32( nMin, tokInt, 0, 59 );
448 if (!bSuccess)
449 return false;
450 if (bFrac)
451 {
452 sal_Int64 fracNumerator;
453 bSuccess = convertNumber64(fracNumerator, tokFrac);
454 if ( bSuccess )
455 {
456 double frac = static_cast<double>(fracNumerator) / pow(static_cast<double>(10), static_cast<double>(tokFrac.getLength()));
457 // seconds
458 OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac minutes (of minutes) not between 0 and 1");
459 frac *= 60;
460 nSec = floor(frac);
461 frac -= nSec;
462 // nanoseconds
463 OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac seconds (of minutes) not between 0 and 1");
464 frac *= 1000000000;
465 nNanoSec = ::rtl::math::round(frac);
466 }
467 goto end;
468 }
469 if(n >= aTimeStr.size())
470 goto end;
471
472 // seconds
473 bSuccess = getISO8601TimeToken(aTimeStr, n, tokInt, bFrac, tokFrac);
474 if (!bSuccess)
475 return false;
476 if (n < aTimeStr.size())
477 {
478 // is it junk or the timezone?
479 bSuccess = getISO8601TimeZoneToken(aTimeStr, n, tokTz);
480 if (!bSuccess)
481 return false;
482 }
483 // max 60 for leap seconds
484 bSuccess = convertNumber32( nSec, tokInt, 0, 60 );
485 if (!bSuccess)
486 return false;
487 if (bFrac)
488 {
489 sal_Int64 fracNumerator;
490 bSuccess = convertNumber64(fracNumerator, tokFrac);
491 if ( bSuccess )
492 {
493 double frac = static_cast<double>(fracNumerator) / pow(static_cast<double>(10), static_cast<double>(tokFrac.getLength()));
494 // nanoseconds
495 OSL_ENSURE(frac < 1 && frac >= 0, "ISO8601parse internal error frac seconds (of seconds) not between 0 and 1");
496 frac *= 1000000000;
497 nNanoSec = ::rtl::math::round(frac);
498 }
499 goto end;
500 }
501
502 end:
503 if (bSuccess)
504 {
505 // normalise time
506 const int secondsOverflow = (nSec == 60) ? 61 : 60;
507 if (nNanoSec == 1000000000)
508 {
509 nNanoSec = 0;
510 ++nSec;
511 }
512 if(nSec == secondsOverflow)
513 {
514 nSec = 0;
515 ++nMin;
516 }
517 if(nMin == 60)
518 {
519 nMin = 0;
520 ++nHour;
521 }
522 if(!tokTz.isEmpty())
523 rTime.IsUTC = (tokTz == "Z");
524
525 rTime.Hours = static_cast<sal_uInt16>(nHour);
526 rTime.Minutes = static_cast<sal_uInt16>(nMin);
527 rTime.Seconds = static_cast<sal_uInt16>(nSec);
528 rTime.NanoSeconds = nNanoSec;
529 }
530
531 return bSuccess;
532}
533
534} // namespace utl
535
536/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
sal_Int16 GetYear() const
sal_uInt16 GetDay() const
sal_uInt16 GetMonth() const
This class can be accessed without locking because we load all of the data in the constructor.
OUString getDate(const Date &rDate) const
only numerical values of Gregorian calendar
OUString getTime(const tools::Time &rTime, bool bSec=true, bool b100Sec=false) const
SvtSysLocale provides a refcounted single instance of an application wide LocaleDataWrapper and <type...
Definition: syslocale.hxx:44
const LocaleDataWrapper & GetLocaleData() const
Definition: syslocale.cxx:146
sal_uInt16 GetSec() const
sal_uInt16 GetMin() const
sal_uInt16 GetHour() const
sal_uInt32 GetNanoSec() const
static const sal_Int64 nanoPerCenti
sal_Int64 n
sal_uInt16 nPos
sal_Int32 getTokenCount(std::string_view rIn, char cTok)
index
sal_Int32 toInt32(std::u16string_view str, sal_Int16 radix=10)
sal_Int64 toInt64(std::u16string_view str, sal_Int16 radix=10)
std::basic_string_view< charT, traits > getToken(std::basic_string_view< charT, traits > sv, charT delimiter, std::size_t &position)
end
OUString toISO8601(const css::util::DateTime &rDateTime)
Definition: datetime.cxx:264
void typeConvert(const Date &_rDate, css::util::Date &_rOut)
Definition: datetime.cxx:234
bool ISO8601parseDate(std::u16string_view aDateStr, css::util::Date &rDate)
convert ISO8601 Date String to util::Date
Definition: datetime.cxx:341
DateTime GetDateTime(const css::util::DateTime &_rDT)
Definition: datetime.cxx:209
OUString GetDateTimeString(const css::util::DateTime &_rDT)
Definition: datetime.cxx:211
const LocaleDataWrapper & GetLocaleData()
Definition: datetime.cxx:203
OUString GetDateString(const css::util::DateTime &_rDT)
Definition: datetime.cxx:229
bool ISO8601parseDateTime(std::u16string_view rString, css::util::DateTime &rDateTime)
convert ISO8601 DateTime String to util::DateTime
Definition: datetime.cxx:305
bool ISO8601parseTime(std::u16string_view aTimeStr, css::util::Time &rTime)
convert ISO8601 Time String to util::Time
Definition: datetime.cxx:381
sal_uInt16 sal_Unicode