-2

How can I convert this one to 12 Hour Format?

Sun Dec 31 14:45:42 GMT+07:36 1899

like this (Ex.)

2:00 PM

Nardong Bagsik
  • 218
  • 6
  • 20
  • Do you have a string or a Date object? There are many, many questions here about [*formatting Dates*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) and reformatting date strings. – RobG Sep 04 '17 at 06:20
  • This is a date object sir – Nardong Bagsik Sep 04 '17 at 06:22
  • In that case, this is a duplicate of [*Where can I find documentation on formatting a date in JavaScript?*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) and the title should be "How to format a Date as hh:mm ap" or similar. A timestamp is a string. – RobG Sep 04 '17 at 06:26

3 Answers3

2

If you're looking for an answer that is specific to Google Apps Script, the most simple fix I can think of is to change the way you define the formatting. Based on the title of this ticket I assume you're using this:

var date = new Date("Sun Dec 31 14:45:42 GMT+07:00 1899");

var date_24hr = Utilities.formatDate(date, 'GMT+7:00', 'EEE MMM dd HH:mm:ss zXX yyyy'); 
// logs Sun Dec 31 14:45:42 GMT+07:00 1899

var date_12hr = Utilities.formatDate(date, 'GMT+7:00', 'EEE MMM dd h:mm:ss a zXX yyyy'); 
// logs Sun Dec 31 02:45:42 PM GMT+07:00 1899

var time_12hr = Utilities.formatDate(date, 'GMT+7:00', 'h:mm a'); 
// logs 02:45 PM

The key is to use lowercase h instead of capital H in the formatDate value.

a10t
  • 21
  • 4
0
var date=new Date(); 

function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

formatAMPM(date); 
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21
0

As you've tagged this as a GAS question, have you looked at Utilities.formatDate()? Documentation here, but in short it takes 3 parameters: a date object, a time-zone string & a format string. The TZ & format are taken from the Java SE SimpleDateFormat class.

In your instance, try this:

var d = new Date("Sun Dec 31 14:45:42 GMT+07:36 1899");
Logger.log(Utilities.formatDate(d, "GMT+07:00", "h:mm a")); // logs 2:09 PM
Dean Ransevycz
  • 933
  • 8
  • 22