我希望能夠使用谷歌應用腳??本在某些條件下將時間 - 小時/分鐘/秒添加或減去特定列。
示例 - 下圖。
A 列是原始時間。
如果 D2 列是“出發至”,則將在原始時間(A2 列)上增加 30 分鐘,這將導致 C2 列中的時間
而如果 D4 列是“到達時間”,將從原始時間(D2 列)中減去 30 分鐘,這將導致 C4 列中的時間。

我可以使用哪個腳本來實作這一目標?
uj5u.com熱心網友回復:
嘗試這個:
function myFunction() {
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getSheetByName("Sheet1");
var range = ss.getRange(2, 1, ss.getLastRow()-1, 4); //get A2:D4 range
var data = range.getDisplayValues(); //get values
data.forEach(row => { // loop each sub-array returned by getDisplayValues
var time = row[0].split(":"); //split the column a to get hour and minutes
var hour = time[0];
var minutes = time[1];
var fDate = new Date(row[1]) //create new Date object by using column b
fDate.setHours(hour) //set the hour of new Date Object
fDate.setMinutes(minutes) //set the minute of new Date Object
if(row[3].toLowerCase() == "depart to"){
fDate.setMinutes(fDate.getMinutes() 30); // add 30 minutes to current date object
row[2] = Utilities.formatDate(fDate, Session.getScriptTimeZone(), "H:mm");
}else if(row[3].toLowerCase() == "arrive from"){
fDate.setMinutes(fDate.getMinutes() - 30); // minus 30 minutes to current date object
row[2] = Utilities.formatDate(fDate, Session.getScriptTimeZone(), "H:mm");
}
})
range.setValues(data) //write values to sheet
}
測驗資料:

輸出:

參考:
- 日期物件
- 電子表格類
- 范圍類
uj5u.com熱心網友回復:
試試這個公式。時間是小時,其中 24 小時 = 1,所以 0.5/24 是半小時。
=IF(D1="Depart To",A1 (0.5/24),A1-(0.5/24))
uj5u.com熱心網友回復:
添加和減去日期
function addsubDates() {
const mA = [...Array.from(new Array(12).keys(), x => Utilities.formatDate(new Date(2021, x, 15), Session.getScriptTimeZone(), "MMM"))];//month array
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const vs = sh.getRange(2, 1, sh.getLastRow() - 1, 4).getDisplayValues();//get as string
let vo = vs.map((r, i) => {
let t = r[0].toString().split(':');
let d = r[1].toString().split('-');
let dt = new Date(parseInt(d[2]), mA.indexOf(d[1]), parseInt(d[0]), parseInt(t[0]), parseInt(t[1]));//base date
let a = 0;
if (r[3].toString().toLocaleLowerCase().includes('arrive')) { a = 30; }//adjustments
if (r[3].toString().toLocaleLowerCase().includes('depart')) { a = -30 }
return [Utilities.formatDate(new Date(dt.valueOf() a * 60000), ss.getSpreadsheetTimeZone(), "HH:mm")];
})
sh.getRange(2, 3, vo.length, vo[0].length).setValues(vo);
}
資料:
| 21:46 | 2020 年 10 月 17 日 | 21:16 | 出發去 |
|---|---|---|---|
| 21:47 | 2020 年 10 月 17 日 | 21:17 | 出發去 |
| 21:48 | 2020 年 10 月 17 日 | 22:18 | 從到達 |
| 21:49 | 2020 年 10 月 17 日 | 22:19 | 從到達 |
| 21:50 | 2020 年 10 月 17 日 | 21:20 | 出發去 |
| 21:51 | 2020 年 10 月 17 日 | 21:21 | 出發去 |
| 21:52 | 2020 年 10 月 17 日 | 22:22 | 從到達 |
| 21:53 | 2020 年 10 月 17 日 | 22:23 | 從到達 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493967.html
上一篇:將格式更改為hh:mm:sss
