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

Magento 2:将Datepicker日期格式改为区域设置默认格式

解决Magento 2日期选择器适配区域设置默认格式的问题

嘿,我来帮你搞定这个问题!要让日期选择器自动匹配当前区域设置(locale)的默认日期格式,不需要手动硬编码dateFormat,可以利用Magento 2自带的JS工具动态获取区域对应的格式,具体操作如下:

方法一:调用日历组件的内置格式获取方法

修改你现有的Knockout绑定代码,把手动设置的dateFormat替换为从当前区域配置中动态获取的格式:

<input class="input-text" type="text" name="customerDob" style="width: 120px" 
       data-validate="{required:true}" 
       data-bind="attr: {'id': getCode() + '-dob'}, 
                  value: customerDob, 
                  datepicker: { 
                      storage: customerDob, 
                      options: {
                          'dateFormat': $.mage.calendar.getDateFormats().short
                      } 
                  }"/>
<div class="mage-error" generated="true" style="display: none;" 
     data-bind="attr: {'id': getCode() + '-dob-error'}"></div>

说明:

  • $.mage.calendar.getDateFormats()会返回当前区域设置对应的三种日期格式:short、medium、long,你可以根据需求选择合适的类型(比如short通常是类似dd/mm/yyyy或mm/dd/yyyy的简洁格式)。
  • 这个方法会自动读取Magento后台配置的区域日期格式,完全适配当前店铺的locale设置。

方法二:利用全局区域格式变量

如果你的页面已经加载了区域设置相关的JS,也可以直接使用全局变量window.dateFormats来获取格式:

<input class="input-text" type="text" name="customerDob" style="width: 120px" 
       data-validate="{required:true}" 
       data-bind="attr: {'id': getCode() + '-dob'}, 
                  value: customerDob, 
                  datepicker: { 
                      storage: customerDob, 
                      options: {
                          'dateFormat': window.dateFormats.short
                      } 
                  }"/>
<div class="mage-error" generated="true" style="display: none;" 
     data-bind="attr: {'id': getCode() + '-dob-error'}"></div>

额外注意事项

  1. 确保依赖组件加载:如果你的自定义模板页面没有自动加载mage/calendar组件,需要在对应的布局XML文件中添加依赖:
<referenceContainer name="before.body.end">
    <block class="Magento\Framework\View\Element\Template" name="calendar.js" template="Magento_Theme::js/calendar.phtml"/>
</referenceContainer>

或者直接在模板中引入:

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "calendar": "mage/calendar"
                }
            }
        }
    }
</script>
  1. 验证区域设置:可以在Magento后台的Stores > Configuration > General > Locale Options中查看当前店铺的区域设置,确认日期格式是否符合预期。

这样修改后,你的日期选择器就会自动根据当前店铺的区域设置显示对应的日期格式,不需要再手动修改硬编码的格式啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:13:59