Timestamp to 12 HR Format (HH:MM AM?PM) - javascript

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

Related

how to get this specific datetime format in javascript

In javascript, is there a way to convert a date time to the following format:
// 11/3/18, 12:00 AM
Date().toString() gives me:
Sat Nov 03 2018 00:00:00 GMT+0000 (UTC)
Thanks.
This is an alternative to format dates, the function Date.prototype.toLocaleDateString allows you to format date according to options/flags.
Some js engines manage the format process differently (so, this is implementation dependent), therefore be careful. Further, you need to check for compatibility in browsers.
let today = new Date();
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour12: true, hour: 'numeric', minute: 'numeric' };
console.log(today.toLocaleDateString('en-US', options));
tl;dr: try typing this in your browser's javascript console on the moment.js website: moment().format('MM/d/YY h:mm A')
Three things:
1. If you haven't already, check out these date docs for the API:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
(Thorough backgrounder): https://www.toptal.com/software/definitive-guide-to-datetime-manipulation
2. Without an external library
See Ele's answer above for most elegant non-library: https://stackoverflow.com/a/53135859/3191929
Ex. Extract mm/dd/yy from Date
const root = new Date();
let month = root.getMonth(); // 0 to 11
let day = root.getDate(); // 1 to 31
let year = root.getFullYear(); year = String(year).slice(2);
// 11/3/18, 12:00 AM mm/dd/yy, hh:mm AM/PM
const output = ``${month}/${day}/${year}``; // mm/dd/yy
And from there you can explore the API to get the 24 hours, then do a check for AM/PM and build the result etc etc. (see bbram's answer here: https://stackoverflow.com/a/8888498/3191929 for the relevant Date APIs for time)
Here's a quick'n'dirty solution to your specific question
Ex. Extract mm/dd/yy hh:mm AM/PM from Date
function formatDate(root) {
let month = root.getMonth(); // 0 to 11, 0 = Jan
month += 1; // 1 to 12, 1 = Jan
let day = root.getDate(); // 1 to 31
let year = root.getFullYear();
year = String(year).slice(2);
// Time transformation appropriated from bbrame
// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format/8888498#8888498
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;
}
// mm/dd/yy, hh:mm AM/PM
const output = `${month}/${day}/${year} ${formatAMPM(root)}`;
return output;
}
var rootDate = new Date();
console.log(formatDate(rootDate)); // mm/dd/yy hh:mm AM/PM
3. With an external library
Using moment.js you can achieve the above with just this:
var root = moment(); // valid moment date
var formatted = root.format('m/d/YY h:mm A');
See the moment.js docs for more details: https://momentjs.com/docs/#/displaying/format/
If momentjs specifically is a no-go, see here for other options as well: https://github.com/you-dont-need/You-Dont-Need-Momentjs

Compare time only when time zone changed in 1920

I have a time value of "7:00:00 AM" in my spreadsheet. Hypothetically, I want to compare this to another hour/minute time value (date agnostic) in my Google Apps Script code. When the script reads the value, because no date was attached, it assumes a date of 30-Dec-1899. Now, the issue is, because the time zone where I currently am was GMT+06:42:04 back in 1899, the time value appears as "07:17:56".
How can I compare this time with another to know if the hours and minutes match? This would ideally be done with vanilla JS (i.e. I prefer not to use Moment.js).
function getCellValue() {
var cellValue = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
Logger.log(cellValue); // Sat Dec 30 07:00:00 GMT+06:42 1899
Logger.log(cellValue.getHours()); // 7.0
Logger.log(cellValue.getMinutes()); // 17.0
Logger.log("Untouched: " + cellValue); // Untouched: Sat Dec 30 1899 07:17:56 GMT+0700 (ICT)
var formattedTime = Utilities.formatDate(cellValue, "GMT+7", "EEE MMM dd yyyy HH:mm z");
Logger.log("Formatted: " + formattedTime); // Formatted: Sat Dec 30 1899 07:17 GMT+07:00
var updatedCellValue = new Date(cellValue.setFullYear(2018));
Logger.log("New Year: " + updatedCellValue); // New Year: Sun Dec 30 2018 07:17:56 GMT+0700 (ICT)
var updatedDate = new Date(cellValue);
Logger.log("Converted: " + updatedDate); // Converted: Sat Dec 30 1899 07:17:56 GMT+0700 (ICT)
Logger.log("Converted & formatted: " + Utilities.formatDate(updatedDate, "GMT+7", "EEE MMM dd yyyy HH:mm z")); // Converted & formatted: Sat Dec 30 1899 07:17 GMT+07:00
}
Both my spreadsheet and script are set to "(GMT+07:00) Bangkok" time zone.
(I understand that 7am today and 7am in 1899 were not the same, but that is irrelevant to this hypothetical. If a user enters 7am in the spreadsheet, they probably mean that to be 7am this century.)
getDisplayValue(), not getValue()
Create a new Date object from value
Use Utilities.formatDate() to get the hour & minutes
Fixed code:
function getCellValue() {
var cellValue = SpreadsheetApp.getActiveSheet().getRange("A1").getDisplayValue();
Logger.log(cellValue); // 7:00:00 AM (or 0.29, if formatted as number)
cellValue = new Date(cellValue);
var hours = Utilities.formatDate(cellValue, "GMT+7", "HH");
var minutes = Utilities.formatDate(cellValue, "GMT+7", "mm");
Logger.log (hours + ":" + minutes); // 07:00
}

Get product given date

How to properly get the date 3 days before the given, if I have a format like 07/21/2017 8:30 AM , this is because I use the format of Eonasdan DateTime Picker. But when I try to minus it with 3 days I got Fri Jul 21 2017 08:24:14 GMT+0800 (China Standard Time) as my value but my desired output should be the same format like 07/21/2017 8:30 AM. How can I get that the value even I follow my format?
My codes:
var d =new Date('07/21/2017 8:30 AM');
var yesterday = new Date(d.getTime() - (96*60*60));
alert(yesterday);
function formatDate(d) {
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
date = [month, day, year].join('/');
var hours = d.getHours();
var minutes = d.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 date+" "+strTime;
}
var d =new Date('07/21/2017 8:30 AM');
d.setDate(d.getDate() - 3);
var yesterday = formatDate(d);
alert(yesterday);
This should work
This should do the trick:
var date = new Date('07/21/2017 8:30 AM'); // get
date.setDate(date.getDate() - 3);
console.log(date.toString());
Basically, it takes the current day with getDate() and uses setDate() to update the time to 3 days in the past.
If you want to format your date, look into moment.js like #Robert said. You could use something like:
moment().format('MM/DD/YYYY, h:mm:ss a');
More information on the Date class here and moment documentation here.
Try using this
var d = new Date();
var d =new Date('07/21/2017 8:30 AM');
var yesterday = d;
yesterday.setDate(d.getDate()-3);
alert(yesterday);
You can simply subtract days from the Date E.g d.getDate() - 3
var d =new Date('07/21/2017 8:30 AM');
d.setDate(d.getDate() - 3);
alert(d)
You need to use setDate function on Date class to change the date part of a date variable
var d =new Date('07/21/2017 8:30 AM');
d.setDate(d.getDate() - 3);
console.debug(d);

how to convert date object of js to time in h:i A (7:30 A.M) format

I have a javascript object of date and its value is:
Thu Dec 18 2014 07:29:44 GMT+0500 (PKT)
Now I want to get the time from above data object in following format:
7:29 A.M
How can I do that using javascript code.
Please Help!!
You can do a little string addition by doing the following:
var result = "";
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var amORpm = hours > 12 ? "P.M" : "A.M";
if(hours > 12) hours -= 12;
result = hours + ":" + minutes + " " + amORpm;
console.log(result); // Will get you your desired format

Parsing date and time from formatted date

I have a date in the following format:
Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)
Can anyone tell me how to parse the date
Wed Jul 17 2013
and time out of this without using string functions
1:00pm
One of the simplest ways is to make sure your LOCALES are set properly, which allows you to do something like this:
var myStrDate = 'Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)';
var myDate = Date.parse(myStrDate);
var myDateOnly = myDate.toLocaleDateString();
var myTimeOnly = myDate.toLocaleTimeString();
Here's a great place to start: http://www.w3schools.com/jsref/jsref_obj_date.asp
You can construct a Date object with the date string, combined with additional functions to get the required output. dayname() returns the dayname, monthname() returns the three-letter month name.
I've used console.info() for outputting results - alert() can be used as an alternative if appropriate.
function dayname(d)
{
var names = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri","Sat" ];
return names[d.getDay()];
}
function monthname(d)
{
var names = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return names[d.getMonth()];
}
// construct new date object passing date string as parameter
var d = new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)");
console.info(dayname(d) + ' ' + monthname(d) + ' ' + d.getDate() + ' ' + d.getFullYear());
For the time, this gettime() function checks the hour to output am or pm correctly, and for correct formatting-:
function gettime(d)
{
var ampm = "am";
var hour = d.getHours();
var mins = d.getMinutes();
if (hour >= 12)
{
hour = hour - 12;
ampm = "pm";
}
if (hours < 10)
hours = "0" + hours;
if (mins < 10)
mins = "0" + mins;
return hour + ":" + mins + ampm;
}
console.info(gettime(d));
var ms = Date.parse(new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)"));
var curr_date = ms.getDate();
var curr_month = ms.getMonth() + 1; //Months are zero based
var curr_year = ms.getFullYear();
var hours = ms.getHours();
var mins = ms.getMinutes();
suf = (hours >= 12)? 'pm' : 'am';
hours = hours % 12;
document.write(curr_date + "-" + curr_month + "-" + curr_year + " " + hours + ":" + min + " " + suffix);
Also try using moment.js, you can format dateTime as you wish.
Here great reference to learn date functions in javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Categories

Resources