MySQL NOW() Returns Only Year - mysql

MySQL docs about NOW() function...
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.
Here's my query...
$sql = "
INSERT INTO `users` ( `username`, `password`, `email`, `time` )
VALUES ('{$username}', '" . sha1( $password ) . "', '{$email}', NOW() )
";
The problem is that in the database I don't have the full datetime, but only the year. Any solutions?

It's int(10) like it was when I used UNIX timestamp.
NOW() works for DATETIME fields only.
You need to either convert your field to DATETIME (the preferable method), or convert NOW() into a UNIX timestamp using UNIX_TIMESTAMP():
UNIX_TIMESTAMP(NOW())

I had this same trouble and was stumped for the longest time till I read this question. I used mysql's now() function to update a member's last login time.
MySQL's now() returns the date time as a string, like YYYY-MM-DD HH:MM:SS - somewhere along the line I stopped using this and started using time() (UNIXTIME) (makes it easier to work with) which returns a string of numbers, like 1352254528. But you can't store a string of numbers like this in a datetime field, and likewise, you can't store YYYY-MM-DD HH:MM:SS in an int(11) field. The latter will result in only the year being stored.
In the end you should use:
int(11) if you're going to use PHP's time() function to store the time as a string of numbers
or
DATETIME field if you're going to use MySQL's NOW() function.

try
strtotime(now())
And you should definitely use timestamp or datetime as a type for your column.

Related

how to change date format in mysql

The default date format in my SQL is : '2019-05-06'
and its fine but when i insert date to my table i want this format 2019-5-6 not the above format
It means month and day must be start 1 to 30 not 01 to 31.Is there any way to change default format in my sql?
You seem to be looking for the MySQL STR_TO_DATE function :
It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.
So if the date coming out of your application is like '2019-5-6', to convert it to a MySQL date you need :
STR_TO_DATE('2019-5-6', '%Y-%c-%e')
In an INSERT statement :
INSERT INTO mytable VALUES(1, STR_TO_DATE('2019-5-6', '%Y-%c-%e'));
Tip :
%Y : Year as a numeric, 4-digit value
%c : numeric month name (0 to 12)
%e: day of the month as a numeric value (0 to 31)
The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD. If you try to enter a date in a format other than the Year-Month-Day format, it might work but it won't be storing the dates as you expect.
In order to run a MySQL Insert command and add the current date into your table you can use MySQL's built-in function CURDATE() in your query.
An example of how to Insert a Date in MySQL using CURDATE
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
Also, you can run a query to set the date manually
An example of how to Insert a Date in MySQL manually
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-7-04')";
It is recommended to do the date formatting when doing a query, like so:
SELECT DATE_FORMAT(BirthDate, "%W %M %e %Y") FROM Employees;
You can find more examples of formatting the date here:
https://www.w3schools.com/sql/func_mysql_date_format.asp

Why doesn't my DateTime search work?

Sorry about the generic title, I didn't know how to phrase this.
I have a DateTime in my MySQL DB. For example: 14/06/2016 15:01:00
When I try to do a query to find dates which equal certain dates it won't find anything, unless I used the Americanised date format. Yet it's stored in the English way.
Eg:
Select * FROM tbl WHERE Date = '14/06/2016' - Doesn't return any results
But Select * FROM tbl WHERE Date = '2016/06/14' does return results.
Why is this? And how can I swap it around?
http://dev.mysql.com/doc/refman/5.7/en/datetime.html
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
If you're seeing a different format, your SQL client is "helpfully" changing the output from the underlying data storage.

Want to run a query which gives me results between two dates. I have timestamp in unix epoch format

I have got timestamps in epoch UNIX format. I want to run a query by directly giving date and not timestamp. How is that possible?
SELECT FROM_UNIXTIME(timestamp)
FROM report_data
WHERE timestamp = '1399376713'
I used this to convert to human readable format.
My database is something like this
timestamp event_type flags
1399357862 701 null
I want to give a particular date in my query and get the result.
It's possible using the FROM_UNIXTIME function.
This assumes that your table contains columns in DATETIME or TIMESTAMP, and you are wanting to supply 32-bit integer values in the query.
For example:
SELECT ...
FROM mytable t
WHERE t.datetime_col >= FROM_UNIXTIME( ? )
AND t.datetime_col < FROM_UNIXTIME( ? )
The integer values supplied as arguments to the FROM_UNIXTIME function will be interpreted as unix-style "seconds since epoch" integer values, and be converted to a DATETIME value using the current timezone setting of the client connection.
This approach will enable MySQL to use a range scan operation using an index with a leading column of datetime_col.
What's not at all clear is what the datatype of your column is, and what values you want to supply in the query. If the columns is datatype DATE, DATETIME or TIMESTAMP (which would be the normative pattern for storing date/time data), then you can specify date literals in standard MySQL format, 'YYYY-MM-DD HH:MM:SS'.
WHERE t.timestamp_col >= '2015-02-11 07:00'
AND t.timestamp_col < '2015-02-11 23:30:00'
If you are storing the "timestamp" as an integer value, then you will need the right side of the predicates to return an integer value, e.g.
WHERE t.integer_col >= UNIX_TIMESTAMP('2015-02-10')
AND t.integer_col < UNIX_TIMESTAMP('2015-02-10' + INTERVAL 24 HOUR)

Difference between UNIX_TIMESTAMP and NOW() in MySQL

I have a blog where users can comment. I insert the time at which they posted a comment using NOW() and then use date('j M Y', stored timestamp) to show the time at which they posted.
I want to know does NOW() return the locatime of the end user or the localtime at my server.
Is it better suited to use UNIX_TIMESTAMP than NOW() to calculate the localtime at which users posted a comment.
The function NOW() generates a formatted date-time string, determined by the time zone of your MySQL server.
However, it would be better to store times using UNIX_TIMESTAMP(), which is expressed in GMT. Doing so makes it easier to format it according to the country of a visitor (e.g. using JavaScript).
If you still want to use DATETIME columns, you can store times using UTC_TIMESTAMP() (it formats a date like NOW() but expresses it in UTC); it should more or less work the same in all other aspects.
MySQL UNIX_TIMESTAMP() returns a Unix timestamp in seconds since '1970-01-01 00:00:00' UTC as an unsigned integer if no arguments are passed with UNIT_TIMESTAMP().
When this function used with date argument, it returns the value of the argument as an unsigned integer in seconds since '1970-01-01 00:00:00' UTC.
Argument may be a DATE, DATETIME,TIMESTAMP or a number in YYYYMMDD or YYMMDD.
Note : Since UNIX_TIMESTAMP() works on current datetime, your output may vary from the output shown.
NOW() returns the current date and time.
SELECT NOW(), UNIX_TIMESTAMP(NOW());
+---------------------+-----------------------+
| NOW() | UNIX_TIMESTAMP(NOW()) |
+---------------------+-----------------------+
| 2011-10-03 10:22:37 | 1317666157 |
+---------------------+-----------------------+
Let's see what the manual has to say about NOW():
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'
or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is
used in a string or numeric context. The value is expressed in the
current time zone.
... and UNIX_TIMESTAMP():
If called with no argument, returns a Unix timestamp (seconds since
'1970-01-01 00:00:00' UTC) as an unsigned integer. 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. date may be a DATE string,
a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or
YYYYMMDD. The server interprets date as a value in the current time
zone and converts it to an internal value in UTC.
So, to begin with, they return different things: a proper date versus an integer.
You actually need to get three features:
Store all dates in the same format (either UTC or the server's time zone)
Obtain user's time zone
Display stored date in user's time zone
The Date and Time functions chapter offers a summary of available functions. If you want to store dates in UTC you'd go for UTC_TIMESTAMP(). If you want to use server's time zone you can use NOW(). And there's CONVERT_TZ() to make conversions.
MySQL, however, won't help you with point #2. You need to either ask the user or use JavaScript to read user's clock and send it to the server so you can guess (if you don't ask you'll always need to guess because there're normally several time zones that share the same time in a given instant).

MySQL date comparison

Dates are stored in DB as such: "2011-05-26 11:00:00" in a datetime field. I'd like to find all rows where the date is greater than the first of this month, ie: 2011-05-01 09:00:00
The date formats in the DB can not be changed. What MySQL function can I use to convert the date in the DB to a format that can handle comparison? I'm guessing the best format for "first of the month" is a unix timestamp?
The time values in the dates are always present but only office hours, so from 09:00 to 17:00.
If it's stored in a DATETIME field, just query on WHERE date > '2011-05-01 09:00:00'.
$firstDayOfMonth = date( 'Y-m-d H:i:s', mktime(0,0,0,date('n'),1,date('Y'));
$query = "SELECT * FROM `table` WHERE `date` >= '$firstDayOfMonth'";
Something like this perhaps?
$oDateTime = new DateTime();
$sQuery = "SELECT * FROM table WHERE date >= ".$oDateTime->format("Y-m")."-01 09:00:00";
Compare to the datetime directly:
WHERE date_field >= '2011-05-01 00:00:00'
DATETIME fields can filtered just like integer fields, example:
SELECT * FROM `table` WHERE `date` > '2011-05-01 09:00:00'
In case you really want to convert to Unix timestamps, have a look at the UNIX_TIMESTAMP function.
You can use TIMESTAMPDIFF function in MySQL to compare time,
FROM_UNIXTIME function to format Unix timestamp as date.
More mysql data and time functions and examples are available in MySQL Reference Manual date and time function .
I think that you can solve it, something like this:
firstly, create first day of month in mysql format in php
$firsDay = date('Y-m-d 00:00:00', strtotime(date('Y-m').'-01 00:00:00'));
and then, use it in the query
select * from something where date >= $firsDay