I need to convert a date like this, 03/07/2016 to a date format like, 2016-03-07.
How can I do this using javascript or jquery?
I need to convert a date like this, 03/07/2016 to a date format like, 2016-03-07.
How can I do this using javascript or jquery?
Assuming your input is a string, this is easy to do using a regular expression with the String .replace()
method:
var input = "03/07/2016";
var output = input.replace(/(\d\d)\/(\d\d)\/(\d{4})/, "$3-$1-$2");
Actually, if the input format is guaranteed, you could just swap the pieces around based on their position without bothering to explicitly match digits and forward slashes:
var output = input.replace(/(..).(..).(....)/, "$3-$1-$2");
Use the split, reverse and join functions:
var yourdate = date.split("/").reverse().join("-");
The split will split the date in various parts, with /
as a delimiter.
The reverse function will reverse all the parts in the array, generated by the split. The join function will join all the parts back together, but now with -
as a delimiter.
Edit
After reading the comments about the date being out of order: swap the second and third values of the array, created by the split function.
var dat = "03/07/2016"
var yourdate = dat.split("/").reverse();
var tmp = yourdate[2];
yourdate[2] = yourdate[1];
yourdate[1] = tmp;
yourdate = yourdate.join("-");
If you want to avoid using regular expressions, manipulating strings, or loading an entire library like moment, you can do this in one line by creating a new JavaScript Date
object with the date you want formatted and calling its toLocaleDateString
method with a compatible locale, such as fr-CA
.
new Date('01/31/2020').toLocaleDateString('fr-CA') // "2020-01-31"
Supported in all modern browsers.
Credit: https://masteringjs.io/tutorials/fundamentals/date_format
const date = new Date();
const convertedDate = date.toLocalDateString('en-IN').split('/').reverse().join('-');
console.log(convertedDate);
Please follow the below method. The trick is to use the unshift property.
function formatDate(__d){
if(__d.indexOf('/')){
var a = __d.split('/')
var b = a.pop()
a.unshift(b)
}
return a.join('-')
}