HRESULT CCppCustomVisualizerService::FileTimeToText()

in CppCustomVisualizer/dll/_EntryPoint.cpp [288:380]


HRESULT CCppCustomVisualizerService::FileTimeToText(const FILETIME& fileTime, CString& text)
{
    text.Empty();

    SYSTEMTIME systemTime;
    if (!FileTimeToSystemTime(&fileTime, &systemTime))
    {
        return WIN32_LAST_ERROR();
    }

    int cch;

    // Deterime how much to allocate for the date
    cch = GetDateFormatW(
        GetThreadLocale(),
        DATE_SHORTDATE,
        &systemTime,
        nullptr,
        nullptr,
        0
        );
    if (cch == 0)
    {
        return WIN32_LAST_ERROR();
    }

    int allocLength = cch
        - 1 // To convert from a character count (including null terminator) to a length
        + 1; // For the space (' ') character between the date and time

    // Deterime how much to allocate for the time
    cch = GetTimeFormatW(
        GetThreadLocale(),
        /*flags*/0,
        &systemTime,
        nullptr,
        nullptr,
        0
        );
    if (cch == 0)
    {
        return WIN32_LAST_ERROR();
    }

    allocLength += (cch - 1); // '-1' is to convert from a character count (including null terminator) to a length
    CString result;
    LPWSTR pBuffer = result.GetBuffer(allocLength);

    // Add the date
    cch = GetDateFormatW(
        GetThreadLocale(),
        DATE_SHORTDATE,
        &systemTime,
        nullptr,
        pBuffer,
        allocLength+1
        );
    if (cch == 0)
    {
        return WIN32_LAST_ERROR();
    }

    pBuffer += (cch-1); // '-1' is to convert from a character count (including null terminator) to a length
    int remainaingLength = allocLength - (cch-1);

    // Add a space between the date and the time
    if (remainaingLength <= 1)
    {
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }
    *pBuffer = ' ';
    pBuffer++;
    remainaingLength--;

    // Add the time
    cch = GetTimeFormatW(
        GetThreadLocale(),
        /*flags*/0,
        &systemTime,
        nullptr,
        pBuffer,
        remainaingLength + 1 // '+1' is for null terminator
        );
    if (cch == 0)
    {
        return WIN32_LAST_ERROR();
    }

    result.ReleaseBuffer();
    text = result;

    return S_OK;
}