[英]Change date input value format
I am implementing a fake form in an HTML page. 我正在HTML页面中实现假表格。 I have several inputs that I need to transform in order to be sent using a POST request. 我有一些输入需要转换才能使用POST请求发送。
One of the problems I am facing is related with the date format. 我面临的问题之一与日期格式有关。 I have a <input type="date">
which returns its value like this: 2017-12-28
, and I need to change its format and turn it into this: 28/12/2017
. 我有一个<input type="date">
,它返回的值是这样的: 2017-12-28
,我需要更改其格式并将其转换为: 28/12/2017
。 I can only use jQuery. 我只能使用jQuery。
Is there a specific function to do this? 有特定的功能可以做到这一点吗? Or do I have to parse it? 还是我必须解析它? I am pretty lost: ( 我很迷路:(
var date = new Date('2017-12-28'); alert(date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear());
Following is the solution without using any plugin. 以下是不使用任何插件的解决方案。
var defaultDate = "2017-12-28"; var splitedValues = defaultDate.split("-"); var newDateFormat = splitedValues[2]+"/"+splitedValues[1]+"/"+splitedValues[0]; console.log(newDateFormat); alert(newDateFormat);
Check this. 检查一下。
var parts = '2017-12-28'.split('-'); var dmyDate = parts[2] + '/' + parts[1] + '/' + parts[0]; console.log(dmyDate);
var userBirthDate = '2017-12-01';
userBirthDate = userBirthDate.split("-").reverse().join("/");
console.log(userBirthDate);
$( function() { $( "#date" ).datepicker(); //set the date format here $( "#date" ).datepicker("option" , "dateFormat", "dd/mm/yy"); } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <input type="text" id="date">
A date input's value is always formatted yyyy-mm-dd
, although the displayed format may vary based on the user's locale. 日期显示的值始终采用yyyy-mm-dd
格式,尽管显示的格式可能会根据用户的区域设置而有所不同。 Parsing it isn't hard though. 解析它并不难。
var myDate = $("#myinput").val().split("-").reverse().join("/")
We get the value from our date input, and split it into parts separated by dashes "-"
. 我们从日期输入中获取值,然后将其分成用破折号"-"
分隔的部分。 So now we have an array like ["2017", "12", "28"]
. 所以现在我们有了一个["2017", "12", "28"]
这样的数组。 Then, we reverse it, so it's in the order we want: ["28", "12", "2017"]
. 然后,我们将其反转,因此它的顺序是我们想要的: ["28", "12", "2017"]
。 Then, we join the elements using slashes, giving us "28/12/2017"
然后,我们使用斜杠加入元素,给我们"28/12/2017"
Please try with this. 请尝试这个。 Something like this 像这样
$(function() {
$( "#datepicker-13" ).datetimepicker({
//format : 'DD-MM-YYYY HH:mm'
viewMode: 'days',
format: 'DD/MM/YYYY'
}, "date");
var dateNow = new Date();
var date= moment(dateNow).format('DD/MM/YYYY');
$('#datepicker-13').attr("value", date);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.