-1

I have a SharePoint page that I am getting a string from and I want to display it on another. The format of the string is as follows: MM/DD/YYYY HH:MM:SS TT. I would like to change it to mmm dd, yyyy.

Mark
  • 2,380
  • 11
  • 29
  • 49

1 Answers1

0

Parsing a date string is pretty simple. It seems you don't care about the time, so you just need to reformat the date part:

function formatDateString(s) {
  var b = s.split(/\D+/g);
  var months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
  return months[--b[0]] + ' ' + b[1] + ', ' + b[2];
}

console.log(formatDateString('08/23/2014 23:32:01 AM')); // Aug 23, 2014

You can also parse the string to create a Date object, then format that:

function parseDateString(s) {
  var b = s.split(/\D+/g);
  var h = b[3]%12 + (('' + b[6]).toLowerCase() == 'am'? 0 : 12);
  return new Date(b[2], --b[0], b[1], h, b[4], b[5]);
}

// Where the local timezone offset is UTC +10:00
console.log(parseDateString('08/23/2014 23:32:01 AM').toISOString()); // 2014-08-23T13:32:01.000Z
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thanks Rob. I will give it a shot tomorrow morning. I appreciate your help! Thanks to @Rocket Hazmat for the link. The timezone code will be very handy going forward. – brentfraser Sep 05 '14 at 01:41
  • &RobG, thanks for the code. Worked like a charm. Thanks to @Rocket Hazmat for the pointer to the timezone code as well. It will come in handy because we have projects that go across multiple timezones. – brentfraser Sep 05 '14 at 14:35