今天在谷歌应用程序脚本中获取日期

时间:2014-07-22 18:07:12

标签: google-apps-script

如何在Google应用脚本中获取今日约会?

我需要编写一个代码来在单元格中输入今天的日期。

function changeDate(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
  var date = //Today´s date!?!?!!?
  var endDate = date;

  sheet.getRange(5, 2).setValue(endDate);

 }

6 个答案:

答案 0 :(得分:30)

Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")

您可以通过交换值来更改格式。

  • dd = day(31)
  • MM =月(12) - 区分大小写
  • yyyy =年(2017)
function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    // You could use now Date(); on its own but it will not look nice.
    var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
    var endDate = date
}

答案 1 :(得分:6)

Date对象用于处理日期和时间。

使用new Date()

创建日期对象
var now = new Date();

now - 当前日期和时间对象。

function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    var date = new Date();
    sheet.getRange(5, 2).setValue(date); 
}

答案 2 :(得分:5)

Google Apps脚本是JavaScript,日期对象是使用new Date()启动的,所有JavaScript方法都适用,see doc here

答案 3 :(得分:2)

最简单的方法,你可以使用 javascript 日期对象,它是 new Date()。

@ControllerAdvice
public class ExceptionHelper {

    static final Logger logger = LoggerFactory.getLogger(ExceptionHelper.class.getName());

    @ExceptionHandler(value = { NullPointerException.class,Exception.class })
    public ResponseEntity<Object> handleException(Exception ex) {
        System.out.println("Inside handleException...");
        String msg="ex="+ex+", ex.getMessage()="+ex.getMessage();
        System.out.println("Exception Msg: "+ msg);
        return new ResponseEntity<Object>(msg, HttpStatus.BAD_REQUEST);
    }
}

但是你会得到整个时间对象。您只需将电子表格中的格式更改为您喜欢的时间或日期即可。

答案 4 :(得分:1)

以下内容可用于获取日期:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

答案 5 :(得分:1)

function myFunction() {
  var sheetname = "DateEntry";//Sheet where you want to put the date
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetname);
    // You could use now Date(); on its own but it will not look nice.
  var date = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");
    //var endDate = date;
    sheet.getRange(sheet.getLastRow() + 1,1).setValue(date); //Gets the last row which had value, and goes to the next empty row to put new values.
}