You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Express+Sequelize项目中如何将日期格式化为DD/MM/YYYY?

解决Express中MySQL日期字段格式化为DD/MM/YYYY的方案

下面提供三种实用的实现方式,你可以根据项目需求选择:

1. 在路由中手动格式化数据

直接在查询到数据后遍历处理日期字段,适合快速修改单个路由的场景:

const Fornecedor = require("../model/Fornecedor")
const Aluguel = require("../model/Aluguel")

router.get('/admin/rent',(req,res)=>{
  Aluguel.findAll().then((alugueis)=>{
    // 遍历并格式化每个数据项的日期字段(假设字段名为dataAluguel,按需修改)
    const formattedAlugueis = alugueis.map(item => {
      const rawDate = item.dataAluguel;
      if (!rawDate) return item.toJSON();
      
      const date = new Date(rawDate);
      const formattedDate = `${String(date.getDate()).padStart(2, '0')}/${String(date.getMonth() + 1).padStart(2, '0')}/${date.getFullYear()}`;
      
      return {
        ...item.toJSON(), // 将Sequelize实例转为普通对象
        dataAluguel: formattedDate
      };
    });

    res.render("aluguel/index", {alugueis: formattedAlugueis})
  }).catch(err => {
    console.error(err);
    res.status(500).send('获取租赁数据失败');
  });
});
  • 注意:使用item.toJSON()将Sequelize模型实例转为普通对象,避免无法修改属性的问题
  • padStart(2, '0')用于保证日期、月份为两位数(如1号转为01,3月转为03)

2. 在Sequelize模型中定义Getter自动格式化

通过模型的getter方法,让所有查询自动返回格式化后的日期,适合全局统一格式的场景:

// ../model/Aluguel.js
module.exports = (sequelize, DataTypes) => {
  const Aluguel = sequelize.define('Aluguel', {
    // 其他字段定义...
    dataAluguel: {
      type: DataTypes.DATE,
      get() {
        const rawValue = this.getDataValue('dataAluguel');
        if (!rawValue) return null;
        
        const date = new Date(rawValue);
        return `${String(date.getDate()).padStart(2, '0')}/${String(date.getMonth() + 1).padStart(2, '0')}/${date.getFullYear()}`;
      }
    }
  }, {
    // 模型配置选项...
  });
  
  // 关联其他模型(如果有)
  Aluguel.associate = models => {
    // ...
  };
  
  return Aluguel;
};

这样你的路由代码无需修改,Aluguel.findAll()返回的每个数据项都会自动携带格式化后的日期字段。

3. 在模板引擎中直接格式化(以EJS为例)

如果仅在特定页面需要格式化,可将逻辑放在前端模板中,路由无需修改数据:

假设你的模板文件是aluguel/index.ejs:

<% alugueis.forEach(aluguel => { %>
  <div class="rental-item">
    <!-- 其他字段渲染... -->
    <p>租赁日期:
      <% 
        const date = new Date(aluguel.dataAluguel);
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
      %>
      <%= `${day}/${month}/${year}` %>
    </p>
  </div>
<% }) %>

这种方式适合不需要在后端保留格式化后数据,仅页面展示需求的场景。

内容的提问来源于stack exchange,提问作者RODRIGO APARECIDO DE ALMEIDA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:45:40