C++Builder 6 and later have a DateTimeToUnix()
function in the DateUtils
unit:
#include <SysUtils.hpp>
#include <DateUtils.hpp>
AnsiString myDateStr = Query->Fields->FieldByName("MyDates")->AsString;
TDateTime myDate = StrToDateTime(myDateStr);
__int64 myTimestamp = DateTimeToUnix(myDate);
If you are using C++Builder 5 or earlier, you can implement your own DateTimeToUnix()
function like this:
#include <SysUtils.hpp>
// Days between TDateTime basis (12/31/1899) and Unix time_t basis (1/1/1970)
const __int64 UnixDateDelta = 25569;
__int64 DateTimeToMilliseconds(const TDateTime &ADateTime)
{
TTimeStamp LTimeStamp = DateTimeToTimeStamp(ADateTime);
return (__int64(LTimeStamp.Date) * MSecsPerDay) + LTimeStamp.Time;
}
__int64 DateTimeToUnix(const TDateTime &AValue)
{
__int64 Result = abs(DateTimeToMilliseconds(UnixDateDelta) - DateTimeToMilliseconds(AValue)) / MSecsPerSec;
if (AValue < UnixDateDelta)
Result = -Result;
return Result;
}
Also note that the version of StrToDateTime()
you are using is subject to the user's current locale settings for date/time. Since you are dealing with a very specific date/time format, I suggest you parse it manually and not rely on any particular locale, eg:
#include <SysUtils.hpp>
#include <stdio.h>
AnsiString myDateStr = Query->Fields->FieldByName("MyDates")->AsString;
Word wYear, wMonth, wDay, wHour, wMin, wSec;
sscanf(myDateStr.c_str(), "%hu-%hu-%hu %hu:%hu:%hu", &wYear, &wMonth, &wDay, &wHour, &wMin, &wSec);
TDateTime myDate = EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMin, wSec, 0);
__int64 myTimestamp = DateTimeToUnix(myDate);
If you are using C++Builder 2006 or later, you can use the overloaded version of StrToDateTime()
that accepts a TFormatSettings
struct as input:
#include <SysUtils.hpp>
#include <DateUtils.hpp>
String myDateStr = Query->Fields->FieldByName("MyDates")->AsString;
TFormatSettings myFmt = TFormatSettings::Create();
myFmt.ShortDateFormat = _D("yyyy-mm-dd hh:nn:ss");
myFmt.DateSeparator = _D('-');
myFmt.TimeSeparator = _D(':');
TDateTime myDate = StrToDateTime(myDateStr, myFmt);
__int64 myTimestamp = DateTimeToUnix(myDate);