Jader Dias
Jader Dias

Reputation: 90475

How to convert DateTime to a number in MySQL?

How can I get the total number of seconds since '1970-01-01 00:00:01' from a DateTime instance in MySQL?

Upvotes: 18

Views: 79367

Answers (4)

Brethlosze
Brethlosze

Reputation: 1612

UNIX_TIMESTAMP(datetime) force a localization of the datetime, which unlike the timestamp, is stored "as is".

You need actually any of the following, for discarding the UTC correction:

UNIX_TIMESTAMP(CONVERT_TZ(datetime, '+00:00', @@session.time_zone))

or:

TIMESTAMPDIFF(SECOND,'1970-01-01 00:00:00',datetime)

Refs: 1, 2, 3, 4

Upvotes: 6

Orson
Orson

Reputation: 15431

SELECT DATE_FORMAT(`value`, '%Y%m%d') AS `date_ymd` FROM `table_name`;

Upvotes: 7

Sven Lilienthal
Sven Lilienthal

Reputation: 6494

You are looking for UNIX_TIMESTAMP().

See: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_unix-timestamp

If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC.

Upvotes: 36

martin clayton
martin clayton

Reputation: 78115

Use UNIX_TIMESTAMP( dateField )

Upvotes: 8

Related Questions