0

I am giving the endDate 2014-07-27 12:00 AM to following code it its generating Jul 28 2014 00:00:00 GMT+0530 (India Standard Time) but i want to display endDate like 2014-07-28 12:00 AM.How can i do it?

endDate = "2014-07-27 12:00";
alert(endDate);
if (endTime == "12:00 AM") {
  endDate = new Date(endDate);
  // add a day
  endDate.setDate(endDate.getDate() + 1);
}
Nick
  • 220
  • 1
  • 2
  • 12
Manjit Singh
  • 255
  • 5
  • 21
  • 1
    Dom't use the Date constructor to parse strings, it's unreliable and implementation dependant. That format will be treated as UTC by some, local by others and `NaN` by a few. Always manually parse strings (there are libraries to help, but it's only two or three lines of code so do it yourself). – RobG Aug 26 '14 at 06:58
  • There is no such thing as 12:00AM. It is 00:00 (midnight). If for some reason you want to display midnight as 12:00AM, you'll have to do it yourself. –  Aug 26 '14 at 07:36
  • @torazaburo—yes, but it is convention to show midnight as 12am and noon as 12pm when writing 12 hour time, annoying as that may be (and that 12:59am comes before 1:00am) – RobG Aug 26 '14 at 07:41

1 Answers1

0

The string:

'2014-07-27 12:00 AM'

does not conform to the format specified in ES5 and therefore how browsers treat it is entirely implementation dependent. Maybe some will treat it as UTC, others may treat it as local and still others won't parse it at all.

You can parse the string yourself, presumably you want it treated as local time:

// Parse a string like 2014-07-27 12:00 AM as a local date and time
function parseISOLike(s) {
  s = s.split(/[- :]/);
  var ap = s[5].toLowerCase();
  var h = s[3]%12 + (ap == 'am'? 0 : 12);
  return new Date(s[0], --s[1], s[2], h, s[4]);
}

Once you have a valid Date object, you can format it however you like using the date methods, e.g.

/* Return time in 12hr format for given Date object, or
** current system time if d is falsey
** e.g. 12:00 AM, 01:15 PM
** If secs is true, also show seconds
** e.g. 12:00:00 AM, 01:15:23 PM
*/
function to12hrTime(d, secs) {
  d = d || new Date();
  var hrs = d.getHours();
  // Pad single digit numbers with a leading zero
  var pad = function(n){return (n<10?'0':'')+ +n};
  return pad(hrs%12 || 12) + ':' + pad(d.getMinutes()) +
         (secs? ':' + pad(d.getSeconds()) : '') +
         ' ' + (hrs<12? 'AM':'PM');
}

// Format date as YYYY-MM-DD hh:mm AP
function formatDate(d) {
  function z(n){return (n<10?'0':'') + n;}
  return d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' +
         z(d.getDate()) + ' ' + to12hrTime(d);
}

console.log(formatDate(parseISOLike('2014-07-27 1:00 pm'))); // 2014-07-27 01:00 PM

There are various libraries that can help with formatting. There is no standard for time zone abbreviations and no reliable method to determine what it might be in javascript, however some libraries do a pretty good job.

RobG
  • 142,382
  • 31
  • 172
  • 209