Article 3J4X1 CodeSOD: Lightweight Date Handling

CodeSOD: Lightweight Date Handling

by
Remy Porter
from The Daily WTF on (#3J4X1)

Darlene has a co-worker who discovered a problem: they didn't know or understand any of the C++ libraries for manipulating dates and times. Checking the documentation or googling it is way too much to ask, so instead they opted to use the tools they already understood- a database. We've seen that before.

There was just one other problem: this application wasn't data-driven, and thus didn't have a database to query.

Darlene's co-worker had the solution to that: create an in-memory Sqlite database!

std::string foo::getTimeStamp(){ static const char *sqlStmt = "SELECT strftime( '%Y-%m-%dT%H:%M:%fZ', CURRENT_TIMESTAMP );"; sqlite3 *db = 0; int sqliteRC = SQLITE_OK; char *sqlErr = 0; // Well we should return something that can be used, so picked an // arbitrary date, which I believe is the time of the first armistice // for the First World War std::string rval = "1918-11-11T11:11:00.000Z"; sqliteRC = sqlite3_open( ":memory:", &db ); if( sqliteRC != SQLITE_OK ) { LOG( Log::Warn ) << "Failed to open sqlite memory DB, with error [" << sqlite3_errmsg( db ) << "]"; return rval; } sqliteRC = sqlite3_exec( db, sqlStmt, &::populate, (void*) &rval, &sqlErr ); if( sqliteRC != SQLITE_OK ) { LOG( Log::Warn ) << "Failed to gather current time stamp" << " from sqlite memory DB with error [" << sqlErr << "]"; sqlite3_free( sqlErr ); } sqliteRC = sqlite3_close( db ); if( sqliteRC != SQLITE_OK ) { // We may leak some memory if this happens LOG( Log::Warn ) << "Failed to close sqlite memory DB with error [" << sqlite3_errmsg( db ) << "]"; } db = 0; return rval;}

This is very lightweight- it's Sqlite, after all. There's nothing light about strftime or its ilk. Just look at the names.

proget-icon.png [Advertisement] Ensure your software is built only once and then deployed consistently across environments, by packaging your applications and components. Learn how today! TheDailyWtf?d=yIl2AUoC8zA6_JOLUSRirM
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments