I have this string:
27/06/2016
or:
15/10/2005
I need to convert the string above to this:
27/06/16
or
15/10/05
How can I implement it in Javascript?
I have this string:
27/06/2016
or:
15/10/2005
I need to convert the string above to this:
27/06/16
or
15/10/05
How can I implement it in Javascript?
Moment.js is the best library to use for date manipulation, it does this easily:
moment('15/10/2005', 'DD/MM/YYYY').format('DD/MM/YY');
Using Regular Expressions
/(?!.*\/)../
str.replace(/(?!.*\/)../,'')
You can use simple string manipulation methods:
function shortDate(str)
{
return str.substring(0, 6) + str.substring(8, 10);
}
var dt = shortDate('27/06/2016');
// returns 27/06/16
function reformat(dateStr)
{
dArr = dateStr.split("/");
return dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);
}
If you are certain the input will always be in exactly that format then you can do it in one line with a simple regex-based string replace:
var output = input.replace(/..(..)$/,"$1");
Of course, you could make the regex more specific with \d for digits, but again if you know the input format is fixed . works fine to do a generic "remove the third- and fourth-last characters from any string".
If you want to work on real dates instead of strings:
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[1], parts[0]);
}
function formatDate(date) {
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear().toString().substr(2);
return day + '/' + month + '/' + year;
}
and then simply:
formatDate(parseDate('27/05/2016')); // returns "27/5/16"
.substr()'s arguments work.)