I got a timestamp record in my msql db which has date and time.
I would to get just the time from it, or just time hour and minute.
How can I split that record?
EDIT here is a picture of my table:
Use MySQL's TIME() function:
SELECT TIME(my_column) FROM my_table
To obtain only the date part, you can use the DATE() function.
Also can try this:
SELECT DATE_FORMAT(now(),'%r') AS timestamp;
| TIMESTAMP |
---------------
| 03:51:43 PM |
SELECT DATE_FORMAT(your_Datetimecolumn,'%r') AS timestamp;
You can also use TIME_FORMAT or DATE_FORMAT to get a specific format e.g. only hh:mm
SELECT TIME_FORMAT( CURRENT_TIMESTAMP, '%H:%i' );
+-------------------------------------------+
| TIME_FORMAT( CURRENT_TIMESTAMP, '%H:%i' ) |
+-------------------------------------------+
| 17:25 |
+-------------------------------------------+
1 row in set (0.00 sec)
EDIT
The function of course works for columns of a table as well
SELECT TIME_FORMAT( myColumn, '%H:%i' ) FROM myTable;
Related
I have a mysql "users" table like this example:
id | user | created
100 | user001 | [27-01-2016 04:30 PM]
101 | user005 | [19-05-2017 09:28 AM]
102 | user019 | [09-10-2015 03:29 PM]
103 | user029 | [18-11-2017 05:40 PM]
And I want to get this table in descending order by created row like this:
id | user | created
103 | user029 | [18-11-2017 05:40 PM]
101 | user005 | [19-05-2017 09:28 AM]
100 | user001 | [27-01-2016 04:30 PM]
102 | user019 | [09-10-2015 03:29 PM]
I tried with DATE_FORMAT:
SELECT id,user,DATE_FORMAT(created,"%d %m %Y") AS created FROM users ORDER by created desc
But it shows nothing, how can I get it?
I'd like some help.
This works:
SELECT `id`, `user`, DATE_FORMAT(STR_TO_DATE(MID(`created`, 2, 19), '%d-%m-%Y %h:%i %p'), '%d-%m-%Y %h:%i %p')
AS `created:` FROM `users` ORDER BY STR_TO_DATE(`created:`,'%d-%m-%Y %h:%i %p') DESC
Here is a working SQL Fiddle.
Explanation:
The MID() MySQL function returns the middle part of a string, so we easily stripped out the []. After that, the STR_TO_DATE() function parses the returned string into DATETIME format (the %p is for AM/PM). The returning value is not properly formatted, at least not in the way you would wish to have it. So we then use DATE_FORMAT() to format the output. In the end, we use STR_TO_DATE() once again for the ordering since created: is returned as string.
I also changed your created output column to created: since it will not work if they are all the same name.
Your created date format isn't correct, you should alter the table and change the field from varchar/char(string) to timestamp type. I have already tried converting your string dates with 'STR_TO_DATE()' but it returns null because the format doesn't match either timestamp, date or time formats. Its always best practice to store dates/datetime as either date or timestamp data types. You can always apply formatting functions later in query to output dates to any desired format.
I need to store a deadline, that consists of a date and a time (e.g 2016-05-02 19:02). I am currently using a field that has DATETIME as datatype but the problem is that its automatically saving it as 2016-05-02 19:02:00.
as a solution i was thinking to save the date in a String field.
So i am wondering if i should do that ? any performance advantages/disadvantages ?
Don't fight the database. Use the builtin types unless you really need something that they can't offer(I'd say it's unlikely, though). (And by this I mean that you should use TIME, DATE or similar for times and dates. Then you can do calculations without having to convert values, etc)
If you don't need the seconds then just keep them 00 all the time.
Whether you use DATETIME, DATE & TIME or perhaps TIMESTAMP is up to you, how you use the data. Choose the alternative that makes most sense in your current situation.
As mentioned in the other answer, you should always use built-in data types whenever possible.
In your case, stick with DATETIME and then convert it to whatever format you need in the query using the DATE_FORMAT function, like so:
mysql> SELECT * FROM `mytable`;
+----+---------------------+
| id | mydatetime |
+----+---------------------+
| 1 | 2016-06-06 14:12:00 |
+----+---------------------+
1 row in set (0.00 sec)
mysql> SELECT DATE_FORMAT(`mydatetime`,'%b %d %Y %h:%i %p') AS `mydatetime` FROM `mytable`;
+----------------------+
| mydatetime |
+----------------------+
| Jun 06 2016 02:12 PM |
+----------------------+
1 row in set (0.00 sec)
Reference:
http://www.w3schools.com/sql/func_date_format.asp
I am working on a project where I have many operations to manage.
Each operation have an end date and is composed by a certain amount of tasks.
I want to display reminders (a text displayed on the screen) if a task is not done before [end date] - X days.
All the data is stored in MySQL database and I work with PHP and HTML5.
Which datatype is (are) the best to work with date and days (to
perform calculations)?
Can I work with Date() and subtract days in a easy way?
I do not have a specific technical question, but I think sharing best way to proceed is a good thing, right?
I'm curious to know what are the best ways to proceed and open to any proposal!
I recommend to store your date in mysql at field timestamp because you can use default value CURRENT_TIMESTAMP - it very helpful,
and i think you shouldn't worry about it, there is a plenty of functions::
mysql:
select now();
+---------------------+
| now() |
+---------------------+
| 2015-04-08 12:13:18 |
+---------------------+
select now() - interval 1 day;
+------------------------+
| now() - interval 1 day |
+------------------------+
| 2015-04-07 12:13:29 |
+------------------------+
select now() - interval 7 day;
+------------------------+
| now() - interval 7 day |
+------------------------+
| 2015-04-01 12:13:38 |
+------------------------+
select now() - interval 1 month;
+--------------------------+
| now() - interval 1 month |
+--------------------------+
| 2015-03-08 12:13:58 |
+--------------------------+
php:
<?php
var_export([
date('Y-m-d H:i:s', strtotime('now')),
date('Y-m-d H:i:s', strtotime('- 1 day')),
date('Y-m-d H:i:s', strtotime('- 7 day')),
date('Y-m-d H:i:s', strtotime('- 1 month')),
]);
/*
Result:
array (
0 => '2015-04-08 15:15:42',
1 => '2015-04-07 15:15:42',
2 => '2015-04-01 15:15:42',
3 => '2015-03-08 15:15:42',
)
*/
And sometimes very helpful to create table like:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
in result your field ts will be automatically seted and updated...
You can store dates as DATETIME in your database.
Then in PHP convert it to manageable data using strtotime() and the date() functions
The best data type to work with is the DateTime class.
In order to perform substractions using the DateTime class, you'll need to use the DateInterval class.
You'll need some time to get on your ease using those two classes but it will make formatting or date operations easier afterwoods.
Here is my table num structure:
mysql> show columns from num;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+-------------------+-----------------------------+
| ip | char(20) | YES | | NULL | |
| time | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
2 rows in set (0.00 sec)
I insert record with the following codes:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$time=$_SERVER['REQUEST_TIME'];
$db=mysql_connect("localhost","root","passwd");
$query="insert into num(ip,time) values('$ip','$time')";
mysql_select_db('numdb');
mysql_query($query, $db);
mysql_close();
echo "ok";
?>
The time is wrong after i inserted two records into table num,
What is matter with my database or php code?
mysql> select * from num;
+-----------+---------------------+
| ip | time |
+-----------+---------------------+
| 127.0.0.1 | 0000-00-00 00:00:00 |
| 127.0.0.1 | 0000-00-00 00:00:00 |
+-----------+---------------------+
2 rows in set (0.00 sec)
To insert the current timestamp, use:
$query="INSERT INTO num(time) VALUES (CURRENT_TIMESTAMP)";
If your server time is different from what you want, you can add hours (or minutes, etc) to the timestamp:
$query="INSERT INTO num(time) VALUES (CURRENT_TIMESTAMP + INTERVAL 6 HOUR)";
It looks like you want to use the REQUEST_TIME value instead of the current time. Fortunately, php makes it easy to convert the string format of the request time into an internal time format, then convert that to the
2015-03-14 15:19:27
standardized string format needed by MySQL to represent a timestamp. This line will give you the workable datestring.
$datestring = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
If you don't care about the distinction between the REQUEST_TIME and the current time, simply don't mention the timestamp column in your INSERT query, and MySQL will use the default (the present time).
Pro tip: Don't name a column timestamp because that's a reserved word. You have to wrap it in backticks in some contexts. Many developers use ts for this.
I want to update mysql rows where DATETIME < TIMESTAMP
DATETIME is like: "2014-06-21 17:56:00"
TIMESTAMP is like 1454546656 (which is now)
I want to update all the rows where DATETIME is in the past
What's the lightest method to deal with a huge number for rows?
Thanks.
In mysql there 2 function which are
from_unixtime() to convert the unix time to human readable date
unix_timestamp() to convert a human readable date to timestamp
So you can use one of then for the comparison
Here how it looks
mysql> select from_unixtime(1454546656);
+---------------------------+
| from_unixtime(1454546656) |
+---------------------------+
| 2016-02-04 06:14:16 |
+---------------------------+
mysql> select unix_timestamp('2014-06-21 17:56:00');
+---------------------------------------+
| unix_timestamp('2014-06-21 17:56:00') |
+---------------------------------------+
| 1403353560 |
+---------------------------------------+
mysql> select unix_timestamp('2014-06-21 17:56:00') < 1454546656;
+----------------------------------------------------+
| unix_timestamp('2014-06-21 17:56:00') < 1454546656 |
+----------------------------------------------------+
| 1 |
+----------------------------------------------------+
mysql> select from_unixtime(1454546656) > '2014-06-21 17:56:00';
+---------------------------------------------------+
| from_unixtime(1454546656) > '2014-06-21 17:56:00' |
+---------------------------------------------------+
| 1 |
+---------------------------------------------------+
So its upto you which one you want to use for the comparison.
Since you are using PHP, try using the PHP Date Function:
$ts = date("Y-m-d H:i:s", $timestamp); //Convert Unix Timestamp to MySQL Date/Time Format
UPDATE table WHERE DATETIME < '$ts';
This is the lightest method I can think of, because it is not recalculating the timestamp for each record, and furthermore, if the DateTime Field is indexed, it will go incredibly fast.