-1

MySQL doesn't save the date properly.I am trying to add createdAt column in database.

I've tried using MySQL NOW() function already, but it doesn't seem to work.

// Go pseudo-code with sql query

stmt, _:= d.db.Prepare("INSERT INTO posts(title, body, EmailHref, SlackHref, DiscordHref, InstHref, Time) VALUES(?, ?, ?, ?, ?, ?, NOW());")
res, err := stmt.Exec(newPost.Title, newPost.Body, newPost.EmailHref, newPost.SlackHref, newPost.DiscordHref, newPost.InstHref)

The type for createdAt column in MYSQL is DATE.

This is what I get when i fetch newly created post:

"time": "2019-04-24T00:00:00Z"

I expect to get actual time with up to minutes.

flyingfox
  • 13,414
  • 3
  • 24
  • 39
E.Belekov
  • 467
  • 1
  • 7
  • 14

2 Answers2

1

In case you want to store the time too, you have to use DATETIME instead of DATE.

You can use the following query to change the column type of column createdAt:

ALTER TABLE posts MODIFY createdAt DATETIME

The DATE data type can't store a time part so you have to use DATETIME:

SELECT CAST(NOW() AS DATE);     -- 2019-04-24
SELECT CAST(NOW() AS DATETIME); -- 2019-04-24 09:47:57
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
0

I think you simple need to change the type from DATE to DATETIME in mySQL

alter table <tableName> modify <columnName> DATETIME;
D.Dsn
  • 176
  • 10
  • @E.Belekov DATE is for storing dates, DATETIME for storing datetimes (dates with times), TIMESTAMPS also stores dates with times, are also faster, but datetime is easier to work with (timezones, sql native functions, ...) – Pavel Třupek Apr 24 '19 at 08:43
  • DATE will simply show you only the date without any time. If you want to add the time you need to change your type to DATETIME or TIMESTAMP – D.Dsn Apr 24 '19 at 08:44
  • Couldn't say it any better @PavelTřupek – D.Dsn Apr 24 '19 at 08:45
  • Whose answer should I accept? You and Sebastian Brosch both answered at the same moment. – E.Belekov Apr 24 '19 at 08:45
  • You can order on oldest an choose the oldest answer, the choice is yours :-) – D.Dsn Apr 24 '19 at 08:47
  • Sorry for the fact that it's been 2 days, thanks anyway! – E.Belekov Apr 26 '19 at 13:31