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
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
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.
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);
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