Harshini Harshini - 2 months ago 18
Javascript Question

Alternative to toLocaleString() for chrome browser

function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];

return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}


The above code, works well in ie browser where I get the output in the following format.

November 13,2012 10:15 AM

But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output?
date.toUTCString()
provides the same result but I am not sure how different it is to
toLocaleString()
in terms of functionality.

Thanks in advance.

Answer

Just do it manually:

// Where "date" is a Date object
function dateFormatUTC(date) {
  var months = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ];

  var hours = date.getUTCHours();
  if (hours < 10) hours = '0' + hours;

  var minutes = date.getUTCMinutes();
  if (hours < 10) hours = '0' + hours;

  var monthName = months[date.getUTCMonth()];
  var timeOfDay = hours < 12 ? 'AM' : 'PM';

  return monthName + ' ' + date.getUTCDate() + ', ' +
         date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
Comments