3
var date = $(this).attr("ows_Date");

My current code displays a string output: 2017-01-02

Is there a Javascript code where I can move the first 4 digit to the back? How do i turn it into 01-02-2017?

Any suggestions?

  • Good suggestion, but can we have a solution on moving numbers instead? – John Lee Nov 29 '17 at 7:37
1

I went really far with this one as the currently accepted answer utilises and manipulates arrays. This could scale quite badly as these functions are quite expensive (compared to alternatives).

The best solution i have found so far is:

function rearrangeDate(dateString) {

  var numbers = dateString.substring(0,4);

  return dateString.substring(5) + '-' + numbers
}

rearrangeDate('2017-01-02'); 

Checkout the relative performance of different approaches here

4
var d=$(this).attr("ows_Date");
var date=new Date(d);
alert((date.getMonth() + 1) + '-' + date.getDate() + '-' +  date.getFullYear())
  • Good suggestion, but can we have a solution on moving numbers instead? – John Lee Nov 29 '17 at 7:37
1

I would prefer using the solution by @Deepmala because it takes into account the date being formatted differently, however if you wanted a 'moving numbers' solution:

function rearrangeDate(dateString) {
  var delimiter = '-';
  var numbers = dateString.split(delimiter);
  var year = numbers.shift(); // remove first element and return it
  numbers.push(year);
  return numbers.join(delimiter);
}

rearrangeDate('2017-01-02'); // '01-02-2017'
1

If SharePoint is loaded then it has added a format option

see: Changing date format using javascript

Makes it a one liner:

String.format("{0:MM}-{0:dd}-{0:yyyy}", new Date("2017-01-02"))

Provided your Browsers date notation matches.. is it Jan 2nd or Feb 1st ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.