Html 如何在html输入中将日期格式更改为dd/mm/yyyy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52127247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:44:22  来源:igfitidea点击:

how to change date format to dd/mm/yyyy in html input

html

提问by Mehedi Hasan Siam

I want to change date format mm/dd/yyyy to dd/mm/yyyy in input filed.

我想在输入字段中将日期格式 mm/dd/yyyy 更改为 dd/mm/yyyy。

My input field

我的输入框

<input placeholder="custom date" type="date"  name="tckt_issue_date">

How can I do this.

我怎样才能做到这一点。

采纳答案by Mehedi Hasan Siam

<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">

回答by Son Nguyen

You will need to add some javascript to the code, please read the following comment

您需要在代码中添加一些 javascript,请阅读以下评论

https://stackoverflow.com/a/31162426/6353996

https://stackoverflow.com/a/31162426/6353996

回答by Daniel Liverant

There is no native way of doing that, but here is my HTML + JS solution:

没有这样做的本地方式,但这是我的 HTML + JS 解决方案:

<script>
function DDMMYYYY(value, event) {
  let newValue = value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '');

  const dayOrMonth = (index) => index % 2 === 1 && index < 4;

  // on delete key.  
  if (!event.data) {
    return value;
  }

  return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');;
}
</script>

<input type="tel" maxlength="10" placeholder="dd/mm/yyyy"
    oninput="this.value = DDMMYYYY(this.value, event)" />

  • It uses the native HTML "oninput" method so the user don't see anything blinking.
  • Using "type=tel" it opens a number keyboard on any mobile device.
  • Basically it's adding '/' after the day and the month and deleting everything else.
  • 它使用原生 HTML“oninput”方法,因此用户看不到任何闪烁的东西。
  • 使用“type=tel”可以在任何移动设备上打开一个数字键盘。
  • 基本上它是在日期和月份之后添加“/”并删除其他所有内容。

Hope it will help someone in the future :)

希望它会在将来对某人有所帮助:)