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;
}

C++ function overloading on Return Type

It is possible to overload the functions based on return type.

I am not talking about the functions with 'CV' qualifier.
For e.g,
class C
{
public:
void foo() const;
int foo() volatile;
double foo() const volatile;
};

This way we can have overloading. But in reality they are not overloaded for same object. It depends on what kind of object. For eg, when you create const object of C, it will call void foo(), similarly for volatile , it is int foo() etc...
So in real sense they are not overloaded.

Where as if you use template, you can overload the functions based on the return type.

class OverLoad
{
public:
template < T > // just declaration , no definition
T GetMe();
};

template <>
int
OverLoad::GetMe()
{
return int;
}

template <>
std::string
OverLoad::GetMe()
{
return std::string();
}template <>

double
OverLoad::GetMe()
{
return 2.2;
}
etc...

These functions can be called by the same object.