2

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?

1

8 Answers 8

3

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');
Sign up to request clarification or add additional context in comments.

2 Comments

this is really good, when you need time manipulations often, and don't have too many js files, coz adding extra 20kb load to your page is somewhat heavy thing. cheers
and still this is beautiful solution
2

Using Regular Expressions

/(?!.*\/)../

str.replace(/(?!.*\/)../,'')

1 Comment

This doesn't work. Try 10/12/2016, or any day in February.
1

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

1 Comment

I was halfway through typing a near identical solution when this appeared!
1

If you are sure that the date is valid you can use this function

function formatDate (input) {
    var datePart = input.match(/\d+/g);
    year = datePart[2].substring(2); // get only two digits
    month = datePart[1];
    day = datePart[0];
    return day+'/'+month+'/'+year;
}

Comments

1

You can follow this procedure.

Old_date = '27/06/2016';
New_date = Old_date.split('/');
New_date[2] = New_date[2].substring(2);
New_date = New_date.join('/');

Comments

0
function reformat(dateStr)
{
dArr = dateStr.split("/");
return dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);     
}

1 Comment

Consider adding some comment to your answer.
0

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".

Comments

0

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"

1 Comment

This won't work because (a) JS dates use zero-based months, and (b) the OP wants two-digit day and month. (Also you should check how .substr()'s arguments work.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.