tags:

views:

108

answers:

3

i want to convert datetime.now() to ticks, like is the time is 4:00 PM on june 18th 2010, i want it to be 20100618160000, or some complex number like this. I want to use this number and another field in my database as the primary keys combination to retrieve data. I am using php and mysql so it would be very helpful if someone could send me some code for the same. Thanks.

SJ

A: 
SELECT UNIX_TIMESTAMP();
websch01ar
A: 

Use strtotime to parse any string representation of a date and time into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)

http://us2.php.net/manual/en/function.strtotime.php

orvado
A: 

I want to use this number and another field in my database as the primary keys combination to retrieve data.

Probably not a good idea. There is the theoretical possibility of a collision when two instances of your script get called at the exact same time. You would have to combine this with another unique value to create a safe primary key.

But to answer your question, microtime(true) will give you the current timestamp with microseconds as one long number. strtotime() will translate about any american-format time into a time stamp.

Pekka
You stop that collision by having the datetime value submitted by the database, not the application. IE: Using NOW()/CURRENT_TIMESTAMP to populate the value is fine.
OMG Ponies
@OMG but it's fine only if you lock the table before inserting the record, isn't it? Or is mySQL clever enough to add something to the second timestamp in case of a collision? After all, we're talking about two script instances with two different database connections here.
Pekka
@Pekka: Operations in a database are queued. There's some mucking when you deal with isolation levels, but otherwise inserts are sequencial.
OMG Ponies
Certainly the best means for having a true identity is to set a PKID with auto-increment set. However, you can use a timestamp as a unique value as well. The database does not typically execute queries at the same exact moment in time. Even if that moment in time is an incredibly small time
websch01ar
@OMG @websch but `CURRENT_TIMESTAMP` alone would still be too rough an identifier, wouldn't it? It counting only seconds, and the likelihood of two operations within the same second being entirely realistic?
Pekka
You would need to go deeper than seconds, yes.
websch01ar
@Pekka: CURRENT_TIMSTAMP is an ANSI synonym for NOW(), which returns datetime to the microsecond - that's what `uuuuuu` is in the format. Just because it's not exposed by default when selecting a datetime, doesn't mean the value isn't there.
OMG Ponies
@OMG ahh, didn't know that. I thought it was seconds only. All right.
Pekka
Wrikken