[英]Convert date format to mm-dd-yyyy with returning string as string and convert dates only in an array?
當我包含['2019-08-11','2019-01-21','2019-11-11']
日期類似時['2019-08-11','2019-01-21','2019-11-11']
我有一個date函數將date轉換為mm-dd-yyyy及其工作正常this.But,在含有我的情況下數組['one','2019-08-01']
當這種情況發生時如何返回我的結果作為, ['one','01-08-2018']
等this.How我可以在JavaScript中實現嗎?
function formatDate(date) {
console.log(date);
console.log('coming');
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [month, day, year].join('-');
}
您可以像這樣將yyyy-mm-dd
轉換為dd-mm-yyyy
:
var str = "2019-08-01"; var formatted = str.split("-").reverse.join("-"); console.log(formatted);
您應該使用moment.js格式化日期。 要檢查使用的有效日期,請使用isValid()
矩函數。
var dateArr = ['one', '2019-08-01']; console.log(getDate(dateArr)); function getDate(arr) { for (var key in arr) { var tempDate = moment(new Date(arr[key])); if (tempDate.isValid()) { arr[key] = tempDate.format('DD-MM-YYYY'); } } return arr; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
這是您的解決方案:
var dates =['one', '2019-03-1', 'try', '2016-01-31','2018-11-11'];
dates.forEach(function(entry) {
//formatDate(entry);
console.log("Got: " + formatDate(entry));
});
;
function formatDate(d) {
console.log(`Processing '${d}'`);
date = new Date(d);
if (isNaN(date)) {
console.log(`'${date}' is not a date.`);
return d;
} else {
console.log(console.log(`'${date}' is a date.`));
return d.split("-").reverse().join("-");
}
}
她是小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.