• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1524
  • Last Modified:

MySQL DateTime NOW() as the default value

Hey there,
need some help with setting my default value in a table to the current datetime
for some reason i cant get the NOW() function to work if i use the DATETIME type.
however, when i use TIMESTAMP type and CURRENT_TIMESTAMP it work!

any ideas how can i get the DATETIME type working?
thanks ahead,
Dan
Capture.PNG
0
maatayim
Asked:
maatayim
  • 2
1 Solution
 
Cornelia YoderArtistCommented:
A mysql function cannot be used as a default.  You will need to use TIMESTAMP field or enter NOW() as part of the values in an INSERT.
0
 
maatayimAuthor Commented:
hi there,
correct me if i'm wrong but timestamp has a differnt way of recording time.
from what i understood the time is being kept in utc and when i retrive is from the data base is converts it back to my timezone.
this could be problematic if u work with servers world wide and try to keep track of dates and times...

is there a ways of using it and still read the real UTC time?
thanks
Dan
0
 
Cornelia YoderArtistCommented:
To convert any date requires you know the time zone of the end user.  That means client-side code, and there are javascript functions that can do that for you.  But it would still be stored in the database as UTC.

http://www.fruitnotes.com/blogs/Javascript_-_converting_unix_timestamp_to_locat_time_format_758

0
 
SoLostCommented:
Firstly, it is inadvisable to have your field named DateTime as DATETIME is a Datatype.  It can potentially cause you headaches.

As previously stated, you can't have a mysql function as the default.

If you can't add NOW() to your MySQL statements then I would look into adding a TRIGGER to your table.

First, set the default value of DateTime in your table to be NULL

While I haven't actually tried this, something like the following may work :
DELIMITER $$

CREATE TRIGGER default_date BEFORE INSERT ON tbl
    FOR EACH ROW BEGIN
        IF NEW.DateTime IS NULL THEN
            SET NEW.DateTime=NOW();
        END IF;
    END;
$$

DELIMITER ;

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now