【问题标题】:How can I insert the UNIX timestamp into a column with my query?如何使用查询将 UNIX 时间戳插入列中?
【发布时间】:2017-07-16 22:13:06
【问题描述】:

如何在我的 MySQL 查询中显示 UNIX 时间戳?它需要采用如下格式:1419245107(所以没有积分等)我找到了一个函数,它是:UNIX_TIMESTAMP(),但我无法让它工作。我希望 UNIX 时间戳进入我的专栏:registrationdate。

我的查询:

var insertQuery = "INSERT INTO penguins (igloos, igloo, moderator, registrationdate, inventory, email, password, username, nickname ) VALUES ('" + "1" + "','" + "1" + "','" + moderator + "','" + registrationdate + "','" + inventory + "','" + email +  "', + UPPER(MD5('" + password + "')), '" + username + "', '"+username+"')";                console.log(insertQuery);

目前,我使用以下方法:

const dateTime = new Date().getTime();
const timestamp = Math.floor(dateTime / 1000);
const registrationdate = timestamp
newUserMysql.registrationdate = registrationdate;

这可行,但它不会更新时间戳。

这实际上是如何工作的?

【问题讨论】:

  • registrationdate 是时间戳吗?那你需要FROM_UNIXTIME(1419245107)
  • 用户注册时,时间戳应该是自动的
  • 然后只需在插入中使用 SQL 的 current_timestamp,例如:...moderator + ", current_timestamp," + inventory...
  • 嗯,它对我不起作用。格式应该是:1500202533,因为我的专栏只接受它。这是我的查询:INSERT INTO penguins (igloos, igloo, moderator, registrationdate, inventory, email, password, username, nickname ) VALUES ('" + "1" + "','" + "1" + "','" + moderator + "','" + ", current_timestamp," + "','" + inventory + "','" + email + "', + UPPER(MD5('" + password + "')), '" + username + "', '"+username+"')"
  • 再次,registrationdate 是时间戳吗?

标签: javascript mysql sql node.js


【解决方案1】:

更改列以包含DEFAULT CURRENT_TIMESTAMP 这会在 TIMESTAMP 或 DATETIME 列中自动插入当前时间戳。如果您实际上为此列使用 INT,请将其更改为使用 DATETIME - 这将使检索、搜索等变得更加容易。 MySQL 内置了用于处理日期和时间的强大设施。更改字段将使用如下命令:

ALTER TABLE `penguins` MODIFY `registrationdate` DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL;

更改列后,将其从 INSERT 语句中删除,否则您将覆盖 DEFAULT 行为:

var insertQuery = "INSERT INTO penguins (igloos, igloo, moderator, inventory, email, password, username, nickname ) VALUES ('1','1','" + moderator + "','" + inventory + "','" + email +  "', + UPPER(MD5('" + password + "')), '" + username + "', '" + username + "')";

【讨论】:

  • @JavaSherwood 什么不起作用? ALTER TABLE 命令还是 DEFAULT CURRENT_TIMESTAMP 的正确操作?我忘记提及(我将编辑)要使用 DEFAULT,您不需要在 INSERT 语句中包含该字段。
  • 请看图。它将所有内容设置为 0
猜你喜欢
  • 1970-01-01
  • 2015-11-18
  • 2019-08-21
  • 2011-08-29
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
相关资源
最近更新 更多