[英]Converting date format from mm/dd/yyyy to yyyy-mm-dd format after entered
在我的日期選擇器中,日期將以 mm/dd/yyyy 格式插入。 但是在我插入后,我希望它以 yyyy-mm-dd 格式發送。 我正在使用 JavaScript 來做到這一點。 但我沒能做到。 所以我該怎么做?
感謝和問候, Chiranthaka
你也可以使用正則表達式:
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
該表達式也適用於個位數的月份和天數。
我為我的網站做了相反的事情,但它可能對你有幫助。 我讓你修改它以適應你的要求。 玩得開心 !
在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;
向 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
正如 Christof R 所說:這也適用於個位數的日期和月份。
// 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.