简体   繁体   中英

Convert date format to mm-dd-yyyy with returning string as string and convert dates only in an array?

I have a date function to convert date to mm-dd-yyyy and its working fine, when my array containing ['2019-08-11','2019-01-21','2019-11-11'] dates like this.But, in my case array containing ['one','2019-08-01'] .when this occurs how to return my result as, ['one','01-08-2018'] like this.How can i achieve this in 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('-');
}

You can transform yyyy-mm-dd into dd-mm-yyyy like so:

 var str = "2019-08-01"; var formatted = str.split("-").reverse.join("-"); console.log(formatted); 

You should use moment.js to format date. To check for valid date used isValid() moment function.

 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> 

Here is your solution:

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("-");
    }
}

Her is a Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM