javascript 输入后将日期格式从 mm/dd/yyyy 转换为 yyyy-mm-dd 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24932343/
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
Converting date format from mm/dd/yyyy to yyyy-mm-dd format after entered
提问by ChiranSJ
In my datepicker the date will be inserted in mm/dd/yyyy format. But after I inserted I want it to be sent in yyyy-mm-dd format. I am using JavaScript to do this. But I wasn't able to do that. So what should I do?
在我的日期选择器中,日期将以 mm/dd/yyyy 格式插入。但是在我插入后,我希望它以 yyyy-mm-dd 格式发送。我正在使用 JavaScript 来做到这一点。但我没能做到。所以我该怎么做?
Thanks & regards, Chiranthaka
感谢和问候, Chiranthaka
回答by Christof R
you could also use regular expressions:
你也可以使用正则表达式:
var convertDate = function(usDate) {
var dateParts = usDate.split(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
return dateParts[3] + "-" + dateParts[1] + "-" + dateParts[2];
}
var inDate = "12/06/2013";
var outDate = convertDate(inDate); // 2013-12-06
The expression also works for single digit months and days.
该表达式也适用于个位数的月份和天数。
回答by ChoiBedal
I did the opposite for my website, but it might help you. I let you modify it in order to fit your requierements. Have fun !
我为我的网站做了相反的事情,但它可能对你有帮助。我让你修改它以适应你的要求。玩得开心 !
Have fun on W3Schools
在W3Schools 上玩得开心
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
if(curr_month < 10)
curr_month = "0"+curr_month;
if(curr_date < 10)
curr_date = "0"+curr_date;
var curr_date_format = curr_date+"/"+curr_month+"/"+curr_year;
回答by TheSatinKnight
Adding more to Christof R's solution (thanks! used it!) to allow for MM-DD-YYYY (- in addition to /) and even MM DD YYYY. Slight change in the regex.
向 Christof R 的解决方案添加更多内容(感谢!使用它!)以允许 MM-DD-YYYY(- 除了 /)甚至 MM DD YYYY。正则表达式略有变化。
var convertDate = function(usDate) {
var dateParts = usDate.split(/(\d{1,2})[\/ -](\d{1,2})[\/ -](\d{4})/);
return dateParts[3] + "-" + dateParts[1] + "-" + dateParts[2];
}
var inDate = "12/06/2013";
var outDate = convertDate(inDate); // 2013-12-06
As Christof R says: This also works for single digit day and month as well.
正如 Christof R 所说:这也适用于个位数的日期和月份。
回答by maggy
// format from M/D/YYYY to YYYYMMDD
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear();
var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
return "".concat(yyyy).concat(mm).concat(dd);
};
var siku = new Date();
document.getElementById("day").innerHTML = siku.yyyymmdd();