1

I currently have this little sinppet of JS that returns a date:

function dateFormatter(date) {
  return date;
}

returns:

Wed Aug 06 2014 14:43:58 GMT+0100 (GMT Standard Time)

How can i adjust that function so it displays something like: Aug 14

I see the output already does Aug but guess the date 2014 to 14 will need something to adjust on that

Thanks in advance

2
  • Date formatting in JS is a massive pain. You dissect the parts of the date using the built in functions, which will work, but is slow to implement and not internationalised. Alternatively you could use Date.js which has all of this taken care of for you. Commented Aug 7, 2014 at 13:39
  • If you want light weight write your own that pulls out the month and year. Seems like a very simple thing to do. Commented Aug 7, 2014 at 13:44

2 Answers 2

3

You should try with momentjs:

function dateFormatter(date) {
  return moment(date).format('MMM YY');
}

With plain JS:

function dateFormatter(date) {
  return date.toString().split(' ')[1] + ' ' + date.getFullYear() % 100;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It is but want to keep this as light weight as possible without loading plugins etc..
0

If you want to format from a Date object, use this:

function formatDate(date) { //takes a Date object
    var monthArr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']; //creates array of month names
    var month = monthArr[date.getMonth()]; //selects array element equal to getMonth(), which ranges from 0-11
    var year = date.getFullYear()%100; //takes the full year (4 digits) mod 100, so the last two digits
    var dateString = month + ' ' + year;
    return dateString;
}

If you want to format a string, like the one you provided, use this:

function formatDate2(str) { //takes a string
    var dateArr = str.split(' '); //creates array from string, splitting by spaces
    var dateString = dateArr[1] + ' ' + dateArr[3].slice(2,4); //gets element 1 (month) and the last two digits of of element 3 (year)
    return dateString;
}

Comments

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.