tags:

views:

110

answers:

2

I have a time_t variable containing a timestamp which I'd like to store in a database, so I need it as a string. How would I convert it.

Also, on the subject, how would I convert a timestamp string into a time_t varible?

Thanks, Wyatt

+1  A: 

Look at ctime, it takes a time_t and returns a string. To make a timestamp from a string, look at mktime. Populate the fields of a struct tm and call mktime. It should return a time_t.

nc3b
Thanks, I'm using this in the meantime, but is there any way to store the ten character timestamp itself? I just find them more easily manipulable.
wyatt
Depending on your database system (postgres, mysql etc) there should be a "date", "datetime", "time" type. For instance mysql has DATETIME and postgres has timestamp. Another (unrecommended) way of doing it would be just storing the timestamp in the database as a 32b integer.
nc3b
Fair enough, but how does one set the timestamp? I don't want them stamped at the current time, the table is a collection of appointments, and the timestamp refers to the start time. Thanks
wyatt
A: 

Since it's tagged C++, I'd recommend this: istringstream http://www.cplusplus.com/reference/iostream/istringstream/

Works like a charm. Might require ostringstream as well.

mathon12
Sorry if I'm being dense, but which function converts from time_t? For that matter, in what format is the data in time_t? cout seems to handle it well enough, but concatenating it into a string results in an unreadable character in the database.
wyatt
Well, assuming time_t here is a 32-bit integer, you can read that into an object of `ostringstream` class, like `oStr<<<time_t variable>`, then maybe push it into it's `iStr` counterpart where you can get its value from its str() method (or something similar). Don't quite remember, but they work like cin/cout and is the easiest way of converting between data types that I can think of.
mathon12
Could you send me the relevant bits of the program? Maybe I can send you a solution back. Need to brush up on my C++ fu.
mathon12