使用`Sequelize.fn`方法格式化SQLite3日期时间的正确方法是什么?

时间:2017-05-29 00:08:42

标签: sqlite sequelize.js

我正在使用MySQL和SQLite3数据库试验Sequelize.js,并在控制台中以JSON格式显示数据。使用MySQL, public class SocketWriteCompletionHandler implements CompletionHandler<Integer, Map<String, Object>> { private static final Logger log = LoggerFactory.getLogger(SocketWriteCompletionHandler.class); @Override public void completed(Integer result, Map<String, Object> attachment) { try { final AsynchronousSocketChannel channel = (AsynchronousSocketChannel) attachment.get("channel"); final ByteBuffer buffer = (ByteBuffer) attachment.get("buffer"); log.info("write {} request to : {}", new String(buffer.array()), channel.getRemoteAddress()); buffer.clear(); readResponse(channel, buffer); } catch (final Exception ex) { ex.printStackTrace(); log.error("an error occured with message : {}", ex.getMessage()); } } @Override public void failed(Throwable exc, Map<String, Object> attachment) { log.error("an error occured : {}", exc.getMessage()); } public void readResponse(AsynchronousSocketChannel channel, ByteBuffer writeBuffer) { final ByteBuffer readBuffer = ByteBuffer.allocate(2 * 1024); final Map<String, Object> attachment = new HashMap<>(); attachment.put("writeBuffer", writeBuffer); attachment.put("readBuffer", readBuffer); attachment.put("channel", channel); readBuffer.flip(); channel.read(readBuffer, attachment, new SocketReadCompletionHandler()); } } 函数可以让我控制Sequelize.fncreatedAt字段的格式,如下所示:

updatedAt

例如:

[Sequelize.fn('date_format', Sequelize.col('updatedAt'), '%m-%d-%Y %H:%i:%s'), 'updatedAt']

返回:

Article.findAll({
    attributes: [
        'id',
        'title',
        'body',
        [Sequelize.fn('date_format', Sequelize.col('createdAt'), '%m-%d-%Y %H:%i:%s'), 'createdAt'],
        [Sequelize.fn('date_format', Sequelize.col('updatedAt'), '%m-%d-%Y %H:%i:%s'), 'updatedAt']
    ]
})
    .then(tasks => {
        console.log(JSON.stringify(tasks, null, 2))
    })

然而,SQLite无法识别 { "id": 27, "title": "This is a test title", "body": "The main body of the article appears here.", "createdAt": "05-28-2017 23:41:42", "updatedAt": "05-28-2017 23:41:42" } 函数并抛出错误:

date_format

研究表明正确的SQLite函数是Unhandled rejection SequelizeDatabaseError: SQLITE_ERROR: no such function: date_format ,但是虽然没有出现错误消息,但输出为strftime。例如,

null

结果

[Sequelize.fn('strftime', Sequelize.col('updatedAt'), '%m-%d-%Y %H:%i:%s'), 'updatedAt']

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

我有同样的问题。你快到了只有Sequelize.fn的参数顺序错误。

[Sequelize.fn('strftime', '%m-%d-%Y %H:%i:%s', Sequelize.col('updatedAt')), 'updatedAt']

您的日期应正确格式化。

感谢您指出正确的方向!