失眠讓我寫這個..
它將format
方法添加到日期對象,無需任何第三方庫和r根據給定的簡寫形式處理格式化的日期。
我基於它PHP's date shorthand,你可以參考。
Date.prototype.format = function(format) {
var months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
format = format.replace(/y/g, ("" + this.getFullYear()).substring(2));
format = format.replace(/Y/g, "" + this.getFullYear());
format = format.replace(/m/g, ("00" + (this.getMonth() + 1)).substr(-2, 2));
format = format.replace(/F/g, months[this.getMonth()]);
format = format.replace(/M/g, months[this.getMonth()].substring(0, 3));
format = format.replace(/n/g, "" + (this.getMonth() + 1));
format = format.replace(/t/g, "" + new Date(this.getFullYear(), this.getMonth() - 1, 0).getDate());
format = format.replace(/D/g, days[this.getDate()].substr(0, 3));
format = format.replace(/d/g, ("00" + this.getDate()).substr(-2, 2));
format = format.replace(/j/g, this.getDate()+"");
format = format.replace(/l/g, days[this.getDate()]);
format = format.replace(/w/g, this.getDay());
format = format.replace(/a/g, this.getHours() > 11 ? "pm" : "am");
format = format.replace(/A/g, this.getHours() > 11 ? "PM" : "AM");
format = format.replace(/g/g, "" + (this.getHours() > 11 ? this.getHours() - 11 : this.getHours() + 1));
format = format.replace(/G/g, "" + (this.getHours() + 1));
format = format.replace(/h/g, ("00" + (this.getHours() > 11 ? this.getHours() - 11 : this.getHours() + 1)).substr(-2, 2));
format = format.replace(/H/g, ("00" + (this.getHours() + 1)).substr(-2, 2));
format = format.replace(/i/g, ("00" + this.getMinutes()).substr(-2, 2));
format = format.replace(/s/g, ("00" + this.getSeconds()).substr(-2, 2));
return format;
};
例子..
// 11/02/16 2:17 AM
var d = (new Date()).format("m/d/y g:i A");
// November 2, 2016, 2:17 am
var d = (new Date()).format("F j, Y, g:i a")
And a fiddle
有沒有真正的速記像PHP和SQL,但也有方法,在短短的返回日期的各部分對任何formatyou可能希望:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date –
@Pamblam問題是,我有一個oracle數據庫,它使用月份的簡寫和從我需要的前端至 發送與查詢參數相同的格式。另外,我跟着你建議實現我迄今爲止所做的相同的鏈接 –
提供了兩種類型的解決方案,希望你喜歡它 –