能否将Google Sheets时间格式设置逻辑从Google Apps Script迁移至PHP?
在PHP中实现Google Sheets时间格式设置的两种方案
完全可以在PHP中实现你的需求,这里提供两种实用方案:
方案1:PHP预格式化时间后再发送到表格
这是最简单的方式——直接在PHP里把要发送的first和last时间字段转成h:mm am/pm格式的字符串,再提交到Google Sheets。表格会自动识别为时间类型并显示成目标格式。
示例代码:
// 假设$firstTime是DateTime对象 $firstTime = new DateTime('2024-05-20 09:30:00'); $formattedFirst = $firstTime->format('h:i A'); // 输出:09:30 AM // 假设$lastTimestamp是时间戳 $lastTimestamp = strtotime('2024-05-20 18:45:00'); $formattedLast = date('h:i A', $lastTimestamp); // 输出:06:45 PM // 后续将$formattedFirst和$formattedLast作为表单字段发送到Google Sheets即可
这种方式无需额外API权限,只要确保发送的格式正确,表格就能直接显示成你要的样式,还能保留时间的可计算属性。
方案2:通过Google Sheets API在PHP中设置列格式
如果需要强制指定H3:H和J3:J列的格式(不管输入内容是什么),可以用PHP调用Google Sheets API批量设置单元格格式。
步骤:
- 在Google Cloud平台启用Sheets API,创建服务账号并下载密钥文件(
service-account-key.json)。 - 安装Google Client PHP库:
composer require google/apiclient:^2.0 - 编写PHP代码发送格式更新请求:
示例代码:
require __DIR__ . '/vendor/autoload.php'; // 初始化Google客户端 $client = new Google\Client(); $client->setAuthConfig('service-account-key.json'); $client->addScope(Google\Service\Sheets::SPREADSHEETS); $sheetsService = new Google\Service\Sheets($client); $spreadsheetId = '你的Google表格ID'; // 从表格URL中获取 $sheetId = 0; // 目标工作表的ID,默认第一个工作表是0 // 构建格式更新请求数组 $requests = [ // 设置H3:H列格式 new Google\Service\Sheets\Request([ 'repeatCell' => [ 'range' => [ 'sheetId' => $sheetId, 'startRowIndex' => 2, // 行索引从0开始,H3对应第3行,索引为2 'startColumnIndex' => 7, // 列索引从0开始,H列对应索引7 'endColumnIndex' => 8 // 结束索引不包含,所以到8为止只选H列 ], 'cell' => [ 'userEnteredFormat' => [ 'numberFormat' => [ 'type' => 'TIME', 'pattern' => 'h:mm am/pm' ] ] ], 'fields' => 'userEnteredFormat.numberFormat' ] ]), // 设置J3:J列格式 new Google\Service\Sheets\Request([ 'repeatCell' => [ 'range' => [ 'sheetId' => $sheetId, 'startRowIndex' => 2, 'startColumnIndex' => 9, // J列对应索引9 'endColumnIndex' => 10 ], 'cell' => [ 'userEnteredFormat' => [ 'numberFormat' => [ 'type' => 'TIME', 'pattern' => 'h:mm am/pm' ] ] ], 'fields' => 'userEnteredFormat.numberFormat' ] ]) ]; // 发送批量更新请求 $batchUpdate = new Google\Service\Sheets\BatchUpdateSpreadsheetRequest([ 'requests' => $requests ]); $sheetsService->spreadsheets->batchUpdate($spreadsheetId, $batchUpdate);
优缺点:
- 优点:一次性设置列格式后,后续无论输入什么时间数据,都会自动套用
h:mm am/pm格式。 - 缺点:需要配置Google Cloud服务账号和API权限,步骤相对繁琐。
内容的提问来源于stack exchange,提问作者missy miss
相关产品推荐
相关产品推荐

