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

如何使用JavaScript将MySQL Timestamp转换为CST时间?

将MySQL Timestamp转换为中部标准时间(CST)并传递给EJS视图

你可以在Node.js后端遍历数据库查询结果,将目标时间字段转换为CST格式后,再传递给EJS视图,具体实现如下:

1. 定义时间转换函数

先编写一个通用函数,将ISO格式的时间字符串转换为美国中部时间(支持自动切换CST/CDT夏令时):

function convertToCST(isoTimestamp) {
  const date = new Date(isoTimestamp);
  return new Intl.DateTimeFormat('en-US', {
    timeZone: 'America/Chicago', // 对应美国中部标准时区的IANA标识符
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false // 可选,设为true则使用12小时制展示
  }).format(date);
}

2. 修改路由处理逻辑

在获取到数据库查询结果后,遍历每条数据转换时间字段(假设你的时间字段名为fecha),再传递给EJS:

rutas.get('/historial', loggedIn, async (req, res, next) => {
    await pool.query('SELECT * FROM historial WHERE id = ? AND  calidaddeltrade = ? OR calidaddeltrade = ?', [req.user.id, 'Excelente', 'Buena'], function (err, rows, fields) {
        if (err) { throw err };
        
        // 处理每条数据的时间字段,保留其他原有字段
        const processedRows = rows.map(row => ({
          ...row,
          fecha: convertToCST(row.fecha)
        }));
        
        res.render('./historial', { rows: processedRows });
        console.log(processedRows);
    })
});

// 时间转换函数
function convertToCST(isoTimestamp) {
  const date = new Date(isoTimestamp);
  return new Intl.DateTimeFormat('en-US', {
    timeZone: 'America/Chicago',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).format(date);
}

补充说明

  • 使用America/Chicago时区标识符会自动适配夏令时切换,比固定UTC偏移量更准确;
  • 如果需要自定义时间格式,可以调整Intl.DateTimeFormat的配置项,比如移除秒数、调整日期展示顺序等;
  • 若你的时间字段名称不是fecha,请替换为实际的字段名。

内容的提问来源于stack exchange,提问作者Andrey Lara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:01:07