简体   繁体   中英

How to reverse date format yyyy-mm-dd using javascript/jquery?

I want to change the date for of data which is in format 2016-10-15 to dm-yy format in jquery as 15-10-2016 .I tried and console the output it shows 2016-10-15 .I caught this result in jquery ajax page which is fetched from database.

$.each(req,function(i,item){
    var val=$.format.date(req[i].from_date, "dd/MMM/yyyy");
    console.log(val);   //'2016-10-15'
});

You can do this work use native javascript functions. Use .split() to split date by - delimiter into array and invert array using .reverse() and convert array to sting using .join()

 var date = "2016-10-15"; date = date.split("-").reverse().join("-"); console.log(date); 

You can do in javascript like this:

var dateAr = '2016-10-15'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0];

console.log(newDate);

Easy with a regex .replace() :

 var input = "2016-10-15"; var output = input.replace(/(\\d{4})-(\\d\\d)-(\\d\\d)/, "$3-$2-$1"); console.log(output); 

You can easily allow the regex to accept several delimeters:

 var re = /(\\d{4})[-. \\/](\\d\\d)[-. \\/](\\d\\d)/; console.log("2015-10-15".replace(re, "$3-$2-$1")); console.log("2015.10.15".replace(re, "$3-$2-$1")); console.log("2015 10 15".replace(re, "$3-$2-$1")); console.log("2015/10/15".replace(re, "$3-$2-$1")); 

You can try like this.

 var OldDate = new Date('2016-10-15');
 var NewDate = OldDate.getDate() + '-' + (OldDate.getMonth() + 1) + '-' + OldDate.getFullYear();

One way to do this :

    var MyDate = '2016-10-15';
    var formattedDate = new Date(MyDate);
    var d = formattedDate.getDate();
    var m =  formattedDate.getMonth();
    m += 1;  // JavaScript months are 0-11
    var y = formattedDate.getFullYear();
    alert(d + "-" + m + "-" + y);

Working Fiddle

You can get date in many formats you refer below code.

 var dateObj = new Date(); var div = document.getElementById("dateDemo"); div.innerHTML = "Date = " + dateObj.getDate() + "<br>Day = " + dateObj.getDay() + "<br>Full Year = " + dateObj.getFullYear() + "<br>Hour = " + dateObj.getHours() + "<br>Milli seconds = " + dateObj.getMilliseconds() + "<br>Minutes = " + dateObj.getMinutes() + "<br>Seconds = " + dateObj.getSeconds() + "<br>Time = " + dateObj.getTime(); 
 <div id="dateDemo"></div> 

format the date as you want.

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