Sample code for 30+ languages & platforms
Unicode C

Compute Difference Between Two DateTime Strings

Demonstrates how to compute the difference between two datetime strings.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkStringBuilderW.h>
#include <C_CkDateTimeW.h>

void ChilkatSample(void)
    {
    const wchar_t *t1;
    const wchar_t *t2;
    HCkStringBuilderW sb1;
    int count;
    HCkStringBuilderW sb2;
    HCkDateTimeW dt1;
    HCkDateTimeW dt2;
    int diffSeconds;

    //  Imagine we have these strings:

    t1 = L"2022-11-14 15:45:38";
    t2 = L"2022-11-16 17:23:41";

    //  How many minutes are between the two?

    //  First, we'd want load each date/time into a Chilkat CkDateTime object.
    //  In this case, there are no CkDateTime methods that accept the above format.
    //  However.. the CkDateTime's SetFromTimestamp will accept a date in the format "YYYY-MM-DDThh:mm:ssZ"

    //  First modify the above dates to the timestamp format.
    sb1 = CkStringBuilderW_Create();
    CkStringBuilderW_Append(sb1,t1);
    count = CkStringBuilderW_Replace(sb1,L" ",L"T");
    CkStringBuilderW_Append(sb1,L"Z");

    sb2 = CkStringBuilderW_Create();
    CkStringBuilderW_Append(sb2,t2);
    count = CkStringBuilderW_Replace(sb2,L" ",L"T");
    CkStringBuilderW_Append(sb2,L"Z");

    //  Load each into a CkDateTime
    dt1 = CkDateTimeW_Create();
    CkDateTimeW_SetFromTimestamp(dt1,CkStringBuilderW_getAsString(sb1));
    //  verify...
    wprintf(L"%s\n",CkDateTimeW_getAsTimestamp(dt1,FALSE));

    dt2 = CkDateTimeW_Create();
    CkDateTimeW_SetFromTimestamp(dt2,CkStringBuilderW_getAsString(sb2));
    //  verify...
    wprintf(L"%s\n",CkDateTimeW_getAsTimestamp(dt2,FALSE));

    //  Get the difference in seconds
    diffSeconds = CkDateTimeW_DiffSeconds(dt2,dt1);
    wprintf(L"Difference in seconds: %d\n",diffSeconds);
    wprintf(L"Difference in minutes: %d\n",diffSeconds / 60);


    CkStringBuilderW_Dispose(sb1);
    CkStringBuilderW_Dispose(sb2);
    CkDateTimeW_Dispose(dt1);
    CkDateTimeW_Dispose(dt2);

    }