performing Arithmetic on SYSTEMTIME

断了今生、忘了曾经 提交于 2019-12-03 16:00:28
Marco

If you're using C# (or VB.NET, or ASP.NET) you can use

DateTime dt = DateTime.Now.AddHours(1);

You can use negative numbers to subtract:

DateTime dt = DateTime.Now.AddHours(-1);

EDITED: I extract an asnwer from this post

They suggest converting SYSTEMTIME to FILETIME, which is a number of ticks since an epoch. You can then add the required number of 'ticks' (i.e. 100ns intervals) to indicate your time, and convert back to SYSTEMTIME.

The ULARGE_INTEGER struct is a union with a QuadPart member, which is a 64bit number, that can be directly added to (on recent hardware).

SYSTEMTIME add( SYSTEMTIME s, double seconds ) {

    FILETIME f;
    SystemTimeToFileTime( &s, &f );

    ULARGE_INTEGER u  ; 
    memcpy( &u  , &f , sizeof( u ) );

    const double c_dSecondsPer100nsInterval = 100. * 1.E-9;
    u.QuadPart += seconds / c_dSecondsPer100nsInterval; 

    memcpy( &f, &u, sizeof( f ) );

    FileTimeToSystemTime( &f, &s );
    return s;
 }

If you want to add an hour use SYSTEMTIME s2 = add(s1, 60*60)

To add signed seconds (forward or backward in time) in C++:

const double clfSecondsPer100ns = 100. * 1.E-9;
void iAddSecondsToSystemTime(SYSTEMTIME* timeIn, SYSTEMTIME* timeOut, double tfSeconds)
{
    union {
        ULARGE_INTEGER li;
        FILETIME       ft;
    };

    // Convert timeIn to filetime
    SystemTimeToFileTime(timeIn, &ft);

    // Add in the seconds
    li.QuadPart += tfSeconds / clfSecondsPer100ns;

    // Convert back to systemtime
    FileTimeToSystemTime(&ft, timeOut);
}
#include <stdio.h>
#include <windows.h>
#define NSEC 60*60

main()
{
SYSTEMTIME st;
FILETIME ft;

// Get local time from system
GetLocalTime(&st);

printf("%02d/%02d/%04d %02d:%02d:%02d\n",
  st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond);

// Convert to filetime
SystemTimeToFileTime(&st,&ft);

// Add NSEC seconds
((ULARGE_INTEGER *)&ft)->QuadPart +=(NSEC*10000000LLU);

// Convert back to systemtime
FileTimeToSystemTime(&ft,&st);

printf("%02d/%02d/%04d %02d:%02d:%02d\n",
  st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!