Chrome与Electron中Date.toLocaleDateString格式不一致的解决方法
解决Chrome与Electron环境下日期格式化不一致的问题
这问题我开发Electron应用时也踩过坑!核心原因是toLocaleDateString()和Intl.DateTimeFormat默认调用时会依赖运行环境的本地化配置——Chrome通常用浏览器自身的区域设置,而Electron可能继承了操作系统的默认区域设置,两者默认locale不一样,自然输出的日期格式就有差异了。
要让两个环境输出完全一致的日期格式,最简单的办法就是显式指定locale和格式化选项,强制日期按照你定义的规则渲染。
具体实现方案
方案1:直接给toLocaleDateString传递参数
如果你想统一成Chrome那种MM/DD/YYYY(比如05/01/2018)的格式,修改render函数里的日期渲染部分即可:
const items = [ { title: 'I am the Title', createdDate: new Date(), id: 'foobazID' } ]; const render = item => (` <table class="table table-striped" id="${item.id}"> <tr> <th>ID:</th><td>${item.id}</td> </tr> <tr> <th>Title:</th><td>${item.title}</td> </tr> <tr> <th>Created At:</th><td>${item.createdDate.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' })}</td> </tr> </table> `); document .getElementById('view') .innerHTML = items.reduce((res, item) => res.concat(render(item)), '') ;
如果想统一成Electron那种YYYY-M-D(比如2018-1-5)的格式,就换成对应的参数:
item.createdDate.toLocaleDateString('zh-CN', { year: 'numeric', month: 'numeric', day: 'numeric' })
方案2:封装复用的日期格式化函数
如果应用里多处需要格式化日期,建议封装单独的函数,方便统一维护:
// 统一日期格式化函数,可根据需求调整规则 const formatCreatedDate = (date) => { return new Intl.DateTimeFormat('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' }).format(date); }; const items = [ { title: 'I am the Title', createdDate: new Date(), id: 'foobazID' } ]; const render = item => (` <table class="table table-striped" id="${item.id}"> <tr> <th>ID:</th><td>${item.id}</td> </tr> <tr> <th>Title:</th><td>${item.title}</td> </tr> <tr> <th>Created At:</th><td>${formatCreatedDate(item.createdDate)}</td> </tr> </table> `); document .getElementById('view') .innerHTML = items.reduce((res, item) => res.concat(render(item)), '') ;
为什么这个方案有效?
当你显式指定locale(比如'en-US')和格式化选项(比如month: '2-digit')时,Chrome和Electron都会严格按照你定义的规则解析、格式化日期,不再依赖环境的默认设置,从而保证输出完全一致。
CSS和HTML部分无需修改,保持原代码即可:
#view { margin: 10px; padding: 10px; border: 1px solid #dee2e6; }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"> <section id="view"> </section>
内容的提问来源于stack exchange,提问作者Hitmands
相关产品推荐
相关产品推荐

