I'm very new to coding and I'm trying to create a simple button in Google Sheets that will take the data from the "input" tab and populate the last empty cells of the appropriate columns in the "feeding" tab. I have it working to log the values of the feedings & date, but can't seem to get them to move.
Here's the code:
//Gets data from 'Input' sheet
function recordData() {
let src = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Input'); //Source
let dst = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Feedings'); //Destination
let input = {};
input.milk = src.getRange('B2').getValue()
input.formula = src.getRange('B3').getValue()
let today = new Date();
today.date = today.getMonth()+1+'/'+today.getDate();
today.formatTime = function formatAMPM (time) {
var hours = time.getHours();
var minutes = time.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 endTime = hours + ":" + minutes + " "+ ampm;
return endTime;
}
today.time = today.formatTime (new Date);
Logger.log("formula = " + input.formula);
Logger.log("milk = " + input.milk);
Logger.log("date = "+ today.date);
Logger.log("time = "+ today.time);
//moves data from 'Input' to 'Feeding' sheet. **NOT WORKING**
function moveData () {
var dstFeedings = {};
dstFeedings.date = dst.getRange("Feedings!A2:A").getLastrow.setValues(today.date);
dstFeedings.time = dst.getRange("Feedings!B2:B").getLastRow.setValues(today.time);
dstFeedings.formula = dst.getRange("Feedings!C2:C").getLastRow.setValues(input.formula);
dstFeedings.milk = dst.getRange("Feedings!D2:D").getLastRow.setValues(input.milk);
return dstFeedings;
}
}
Here's the link to a copy of the sheet
The code in the question has at least two problems, getLastRow and setValues, on
dstFeedings.date = dst.getRange("Feedings!A2:A").getLastrow.setValues(today.date);
dstFeedings.time = dst.getRange("Feedings!B2:B").getLastRow.setValues(today.time);
dstFeedings.formula = dst.getRange("Feedings!C2:C").getLastRow.setValues(input.formula);
dstFeedings.milk = dst.getRange("Feedings!D2:D").getLastRow.setValues(input.milk);
getLastRow hasn't a setValues method.
setValues requires and Array having an Array for each row, the inner Array, should have a value or Date object for each row's cell. Since the variables used hold a single value / Date object, setValue should be used instead of setValues.
Related
More efficient way too look up the last row in a specific column?
Finding an empty cell in a column using google sheet script
How to find the last cell with a value at the end of a column that is shorter than other columns in Google Sheets?
I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.
I get the current date time with new Date()
I know I can calculate the timespan in seconds by using
const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;
Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?
An example would be new Date('12:45')
var minutes = 42;
for (var hours = 1; hours < 24; hours+=3) {
var newAlarm = setAlarm(hours, minutes);
out(newAlarm)
}
function out(date) {
var now = new Date()
if (date.getDate() != now.getDate()) {
console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
} else {
console.log('today: ' + date.getHours() + ":" + date.getMinutes())
}
}
function setAlarm(hours, minutes) {
var now = new Date();
var dateTarget = new Date();
dateTarget.setHours(hours)
dateTarget.setMinutes(minutes)
dateTarget.setSeconds(0)
dateTarget.setMilliseconds(0)
if (dateTarget < now) {
dateTarget.setDate(dateTarget.getDate()+1)
}
return dateTarget
}
See this Documentation on MDN
You can manipulate the date and then check whether it is in the past. If it is, just add another day.
const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
if (d < new Date()) {
d.setDate(d.getDate() + 1);
}
console.log(d);
It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):
const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)
I have a ajax call which returns a time e.g 16:06:59 i want to convert it to 4:06 PM
var mydate = obj[0].time;
mydate comes 16:06:59 but when i try to use it with var date = new Date(), it gives me todays date .
Is there any solution to realize what i want ?
Thanks
The simplest answer is to split it into parts and then use them however you want, e.g.:
var parts = obj[0].time.split(":");
// parts[0] is now "16"
// parts[1] is now "06"
// parts[2] is now "59"
// Then perhaps (to get numbers and give the parts names)
var hours = parseInt(parts[0], 10);
var minutes = parseInt(parts[1], 10);
var seconds = parseInt(parts[2], 10);
...and of course for the first one you can use:
if (hours > 12) {
hours -= 12;
}
...if you want to do the a.m./p.m. thing. Just remember you did that and set your a.m./p.m. variable accordingly.
If you really want a Date instance, you can do this:
var dt = new Date();
dt.setHours(hours); // Be sure to use the real value here, not the one -12
dt.setMinutes(minutes);
dt.setSeconds(seconds);
try this :
function Convert24HoursTo12(time) {
var timeArray = time.split(':');
var hours = timeArray[0];
var minutes = timeArray[1];
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
and call it:
Convert24HoursTo12(obj[0].time);
See Demo Here.
You can do this:
"16:06:59".split(':').slice(0, 2)
.map(function (x, index) {
return index == 0 ? (x > 12 ? x - 12 + "PM" : x + "AM") : x
}).join(":").replace(/(.+?)((P|A)M)(.+)/, "$1$4 $2");
Modify the following code according to your need
var mydate= new Date();
var myhour=mydate.getHours();
var ampm="AM";
if(myhour==12)ampm="PM";
if(myhour==0)myhour=12;
if (myhour>12){
myhour-=12;
ampm="PM";
}else{
myhour=mydate.getHours();
}
var mytime=myhour+":"+mydate.getMinutes()+":"+mydate.getSeconds()+" "+ampm;
then use mytime variable anywhere you want
I have not checked it as I am in a hurry now. I hope it works well.
I'm working on a script which would create a countdown timer based on string date and time that the admin defines. I have it already coded, however, there is a problem of users seeing different timers depending on their timezone. For instance, if the admin set the date and time to today, 4:50 PM (an hour from now), he'd see the timer at 01:00:00, while I'd see it at 04:00:00. Obviously, I'd like the timer to display the same for everyone.
Any ideas?
Here's part of the code:
//stringDate is the date and time string the admin sets
var splitSD = stringDate.split(' ');
//isolate date, time, notation
var splitDate = splitSD[0];
var splitTime = splitSD[1];
var splitNotation = splitSD[2];
//isolate month, day, year
var formatDate = splitDate.split('/');
formatDate['month'] = formatDate[0];
formatDate['day'] = formatDate[1];
formatDate['year'] = formatDate[2];
//isolate hour, minute, second
var formatTime = splitTime.split(':');
formatTime['hour'] = formatTime[0];
formatTime['minute'] = formatTime[1];
formatTime['second'] = '00';
//change hour to 24-hour clock based on notation
if(splitNotation == 'PM' && parseInt(formatTime['hour'])<12){
formatTime['hour'] = parseInt(formatTime['hour']) + 12;
}
if(splitNotation == 'AM' && parseInt(formatTime['hour'])==12){
formatTime['hour'] = parseInt(formatTime['hour']) - 12;
}
//prepend 0 in case...
formatDate['month'] = (formatDate['month'].length == 1) ? '0'+formatDate['month'] : formatDate['month'];
formatDate['day'] = (formatDate['day'].length == 1) ? '0'+formatDate['day'] : formatDate['day'];
formatTime['hour'] = (formatTime['hour'].length == 1) ? '0'+formatTime['hour'] : formatTime['hour'];
formatTime['minute'] = (formatTime['minute'].length == 1) ? '0'+formatTime['minute'] : formatTime['minute'];
//format full date and prevent conversion to local time
var fullFD = new Date(formatDate['year'] + '-' + formatDate['month'] + '-' + formatDate['day'] + 'T' + formatTime['hour'] + ':' + formatTime['minute'] + ':00-08:00');
//make timestamp
var fullFDTimestamp = Math.round(fullFD / 1000);
return fullFDTimestamp;
Answer-ing my comment, as requested.
Use Date.prototype's getTimezoneOffset method. It gives the difference, in minutes, between the local time and GMT UTC. You can calibrate the countdown timer to take into account this offset value and show the desired time.
I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45, str2 contains 5:10:10.
How can I compare the above values?
As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:
var str1 = "10:20:45",
str2 = "05:10:10";
if (str1 > str2)
alert("Time 1 is later than time 2");
else
alert("Time 2 is later than time 1");
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true
The 1st January is an arbitrary date, doesn't mean anything.
Date object in js support comparison, set them same date for compare hh:mm:ss :
new Date ('1/1/1999 ' + '10:20:45') > new Date ('1/1/1999 ' + '5:10:10')
> true
Try this code for the 24 hrs format of time.
<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");
var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();
if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>
You can easily do it with below code:
Note: The second argument in RegExp is 'g' which is the global search flag.
The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern. Below code only works if the time is in HH:MM:SS format i.e. 24 hour time format.
var regex = new RegExp(':', 'g'),
timeStr1 = '5:50:55',
timeStr2 = '6:17:05';
if(parseInt(timeStr1.replace(regex, ''), 10) < parseInt(timeStr2.replace(regex, ''), 10)){
console.log('timeStr1 is smaller then timeStr2');
} else {
console.log('timeStr2 is smaller then timeStr1');
}
Try this code.
var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}
Convert to seconds those strings:
var str1 = '10:20:45';
var str2 = '5:10:10';
str1 = str1.split(':');
str2 = str2.split(':');
totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[0]);
totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[0]);
// compare them
if (totalSeconds1 > totalSeconds2 ) { // etc...
Best way to compare times using convert into ms
var minutesOfDay = function(m){
return m.minutes() + m.hours() * 60;
}
return minutesOfDay(now) > minutesOfDay(end);
I improved this function from #kamil-p solution.
I ignored seconds compare . You can add seconds logic to this function by attention your using.
Work only for "HH:mm" time format.
function compareTime(str1, str2){
if(str1 === str2){
return 0;
}
var time1 = str1.split(':');
var time2 = str2.split(':');
if(eval(time1[0]) > eval(time2[0])){
return 1;
} else if(eval(time1[0]) == eval(time2[0]) && eval(time1[1]) > eval(time2[1])) {
return 1;
} else {
return -1;
}
}
example
alert(compareTime('8:30','11:20'));
Thanks to #kamil-p
I think you can put it like this.
var a = "10:20:45";
var b = "5:10:10";
var timeA = new Date();
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);
timeB = new Date();
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);
var x= "B is later than A";
if(timeA>timeB) x = "A is later than B";
document.getElementById("demo").innerHTML = x;
<p id="demo"></p>
Set the extracted part of the time to variables.
// If you don't have the second part then set it to 00.
//Create date object and set the time to that
var startTimeObject = new Date();
startTimeObject.setHours(startHour, startMinute, startSecond);
//Create date object and set the time to that
var endTimeObject = new Date(startTimeObject);
endTimeObject.setHours(endHour, endMinute, endSecond);
//Now we are ready to compare both the dates
if(startTimeObject > endTimeObject) {
alert('End time should be after start time.');
}
else {
alert('Entries are perfect.');
}
time format should be in HH:mm:ss HH for 24 hour format
if (start_time > end_time)
console.log('start time is greater than end time')
else console.log('end time is greater than start time')
You could compare the two values right after splitting them with ':'.
I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.
function compareDateTimes() {
//date format ex "04/20/2017 01:30PM"
//the problem is that this format results in Invalid Date
//var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date
var start_date = $(".letter #depo_arrival_time").val();
var end_date = $(".letter #depo_dateandtime").val();
if (start_date=="" || end_date=="") {
return;
}
//break it up for processing
var d1 = stringToDate(start_date);
var d2 = stringToDate(end_date);
var diff = d2.getTime() - d1.getTime();
if (diff < 0) {
end_date = moment(d2).format("MM/DD/YYYY hh:mA");
$(".letter #depo_arrival_time").val(end_date);
}
}
function stringToDate(the_date) {
var arrDate = the_date.split(" ");
var the_date = arrDate[0];
var the_time = arrDate[1];
var arrTime = the_time.split(":");
var blnPM = (arrTime[1].indexOf("PM") > -1);
//first fix the hour
if (blnPM) {
if (arrTime[0].indexOf("0")==0) {
var clean_hour = arrTime[0].substr(1,1);
arrTime[0] = Number(clean_hour) + 12;
}
arrTime[1] = arrTime[1].replace("PM", ":00");
} else {
arrTime[1] = arrTime[1].replace("AM", ":00");
}
var date_object = new Date(the_date);
//now replace the time
date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
date_object = new Date(date_object);
return date_object;
}
var str1 = "150:05:05",
var str2 = "80:04:59";
function compareTime(str1, str2){
if(str1 === str2){
return 0;
}
var time1 = str1.split(':');
var time2 = str2.split(':');
for (var i = 0; i < time1.length; i++) {
if(time1[i] > time2[i]){
return 1;
} else if(time1[i] < time2[i]) {
return -1;
}
}
}
var startTime = getTime(document.getElementById('startTime').value);
var endTime = getTime(document.getElementById('endTime').value);
var sts = startTime.split(":");
var ets = endTime.split(":");
var stMin = (parseInt(sts[0]) * 60 + parseInt(sts[1]));
var etMin = (parseInt(ets[0]) * 60 + parseInt(ets[1]));
if( etMin > stMin) {
// do your stuff...
}