Upraviť

Zdieľať cez


Warning C26862

A date-time object var has been created from a different type of date-time object but conversion was incomplete: expr

This rule was added in Visual Studio 2022 17.8.

Remarks

Proper enforcement of leap year and leap day handling rules require tracking the proper conversion between date-time objects of different types such as the Windows SYSTEMTIME struct and the C tm struct. Different date-time types may have different bases for the year, month, and day fields. For example, SYSTEMTIME has a 0-based year, but 1-based month and day fields. On the other hand, tm has a 1900-based year, a 0-based month, and a 1-based day fields. To convert an object of one of these types to an object of another type, the year, month, and day fields must be adjusted appropriately.

Code analysis name: INCOMPLETE_DATETIME_CONVERSION

Example

The following code tries to convert an instance of tm into an instance of SYSTEMTIME. It makes the necessary adjustment to the year field, but doesn't properly adjust the month field:

#include <Windows.h>
#include <ctime>
  
void ConvertTmToSystemTime1b(const tm& tm) 
{ 
    SYSTEMTIME st; 
    st.wYear = tm.tm_year + 1900; 
    st.wMonth = tm.tm_mon; // C26862, Adjustment is missing 
    st.wDay = tm.tm_mday; 
} 

To fix this problem, adjust the month and year fields:

#include <Windows.h> 
#include <ctime> 
  
void ConvertTmToSystemTime(const tm& tm) 
{ 
    SYSTEMTIME st; 
    st.wYear = tm.tm_year + 1900; 
    st.wMonth = tm.tm_mon + 1; 
    st.wDay = tm.tm_mday; 
} 

Heuristics

This rule only recognizes the Windows SYSTEMTIME struct and the C tm struct.

This rule is an opt-in rule, meaning that code analysis should use a ruleset file, and the rule should be explicitly included in the ruleset file, and enabled for it to be applied. For more information on creating a custom ruleset for code analysis, see Use Rule Sets to Specify the C++ Rules to Run.

See also

C6393
C6394
C26861
C26863
C26864