使用App Script将表格中的24小时制转换为12小时制

时间:2014-10-01 17:00:51

标签: google-apps-script

我目前正在使用Forms来收集特定时间的数据。问题是,虽然以12小时格式询问,但它以24小时格式返回。 (即表格中的下午1点在Logger活动中显示13:00)有没有办法将24小时转换回12小时?我正在使用的代码如下。

function onFormSubmit(e) {

  var submissionSSKey = 'WorkSheet ID';
  var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
  var lastRow = sheet.getLastRow();

  var PUStartTime = e.response.getItemResponses()[4].getResponse(); //Needs to be in 12-hour
  var PUEndTime = e.response.getItemResponses()[5].getResponse(); //Needs to be in 12-hour

  var joinedTimes = (PUStartTime + " - " + PUEndTime); //This is why I need 12-hour times

  var targetRange = sheet.getRange(lastRow+1, 1, 1, 1).setValues([[joinedTimes]]);
}

2 个答案:

答案 0 :(得分:2)

如果您的PUEndTime变量采用日期格式,

也许尝试使用formatDate()实用程序?

Google Documentation - Format Date

var endTime = Utilities.formatDate(PUEndTime, "GMT", "hh:mm a");

h =上午/下午(1-12)小时

a = Am / pm标记

Date and Time patterns reference

答案 1 :(得分:1)

这是我如何完成这个的最终版本。可以使用此处的示例更改时间布局:Date and Time Preference reference

function onFormSubmit(e) {

  var submissionSSKey = 'WorkSheet ID';
  var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
  var lastRow = sheet.getLastRow();

  //Get current time
  var d = new Date();

  var PUStartTime = e.response.getItemResponses()[4].getResponse();
     var split = PUStartTime.split(":"); //Split the time submitted from user on Forms
        var part1 = split[0];
        var part2 = split[1];
          d.setHours(part1) //Set the current hour to user submitted hours
          d.setMinutes(part2) //Set the current minute to user submitted minutes
  //Format the time to how we want it
  var startTime = Utilities.formatDate(d, Session.getScriptTimeZone(), "h:mm a");


  var PUEndTime = e.response.getItemResponses()[5].getResponse();
    var split = PUEndTime.split(":"); //Split the time submitted from user on Forms
        var part1 = split[0];
        var part2 = split[1];
          d.setHours(part1) //Set the current hour to user submitted hours
          d.setMinutes(part2) //Set the current minute to user submitted minutes
  //Format the time to how we want it
  var endTime = Utilities.formatDate(d, Session.getScriptTimeZone(), "h:mm a");

  //Joining those new 12-hour times together
  var joinedTimes = (startTime + " - " + endTime); 

  var targetRange = sheet.getRange(lastRow+1, 1, 1, 1).setValues([[joinedTimes]]);
}