Tuesday, March 30, 2010

Oracle Timestamp conversion from epoch and vice-versa

I searched the net but didn't get the code so publishing it here.

class OracleTimeStamp
{
public:
static Timestamp ToTimestamp(Oracle::ENV env, const struct timeval &tv);
static void ToEpoch(const Timestamp& ts, struct timeval &tv);
};

Timestamp
OracleTimeStamp::ToTimestamp(Oracle::ENV env, const struct timeval &tv)
{
char buffer[100] = {0};
time_t curtime = tv.tv_sec;

strftime(buffer,30,"%Y %m %d %H %M %S",localtime(&curtime));

stringstream strstream;
strstream.clear();
strstream << buffer << " " << tv.tv_usec;

int year;
int month;
int day;
int hour;
int minute;
int seconds;
long int millisec;

strstream >> year;
strstream >> month;
strstream >> day;
strstream >> hour;
strstream >> minute;
strstream >> seconds;
strstream >> millisec;
millisec *= 1000;
Timestamp ts(env, year, month, day, hour, minute, seconds, millisec);
return ts;
}



void
OracleTimeStamp::ToEpoch(const Timestamp& ts, struct timeval &tv)
{
string date_time = ts.toText("yyyy mm dd hh24:mi:ss.FF", 6);
date_time.replace(13, 1, " ");
date_time.replace(16, 1, " ");
date_time.replace(19, 1, " ");

stringstream date_time_stream;
date_time_stream.clear();
date_time_stream << date_time;

struct tm time_val;
date_time_stream >> time_val.tm_year;
time_val.tm_year -= 1900;
date_time_stream >> time_val.tm_mon;
time_val.tm_mon -= 1;
date_time_stream >> time_val.tm_mday;
date_time_stream >> time_val.tm_hour;
date_time_stream >> time_val.tm_min;
date_time_stream >> time_val.tm_sec;

date_time_stream >> tv.tv_usec;

// Assign the values to struct tm
// Then get the microsecond value directly into tv.tv_usec
time_t time_in_sec;
time_in_sec = mktime(&time_val);
tv.tv_sec = time_in_sec;
return;
}

No comments: