tdf#154285 Check upper bound of arguments in SbRtl_Minute function
[LibreOffice.git] / tools / source / datetime / systemdatetime.cxx
blob5bc785b42cfbfdd52895f5a53346ef2e96818f07
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2 /*
3 * This file is part of the LibreOffice project.
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/.
9 * This file incorporates work covered by the following license notice:
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 .
20 #include <sal/config.h>
22 #include <chrono>
23 #include <time.h>
25 #include <systemdatetime.hxx>
27 namespace
29 constexpr sal_Int32 ConvertYMDToInt(sal_Int32 nYear, sal_Int32 nMonth, sal_Int32 nDay)
31 return (nYear * 10000) + (nMonth * 100) + nDay;
34 constexpr sal_Int64 ConvertHMSnToInt(sal_Int64 nHour, sal_Int64 nMin, sal_Int64 nSec,
35 sal_Int64 nNanoSec)
37 return (nHour * HOUR_MASK) + (nMin * MIN_MASK) + (nSec * SEC_MASK) + nNanoSec;
41 bool GetSystemDateTime(sal_Int32* pDate, sal_Int64* pTime)
43 auto tp = std::chrono::system_clock::now();
44 const time_t nTmpTime = std::chrono::system_clock::to_time_t(tp);
45 struct tm aTime;
46 #if defined(_WIN32)
47 bool ok = localtime_s(&aTime, &nTmpTime) == 0;
48 #else
49 bool ok = localtime_r(&nTmpTime, &aTime) != nullptr;
50 #endif
51 if (ok)
53 if (pDate)
54 *pDate = ConvertYMDToInt(static_cast<sal_Int32>(aTime.tm_year + 1900),
55 static_cast<sal_Int32>(aTime.tm_mon + 1),
56 static_cast<sal_Int32>(aTime.tm_mday));
57 if (pTime)
59 auto hms = std::chrono::hh_mm_ss(std::chrono::floor<std::chrono::nanoseconds>(
60 tp - std::chrono::floor<std::chrono::days>(tp)));
61 auto ns = hms.subseconds().count();
62 *pTime = ConvertHMSnToInt(aTime.tm_hour, aTime.tm_min, aTime.tm_sec, ns);
64 return true;
67 return false;
70 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */