在Google Apps脚本中将字符串转换为日期

在Google Apps脚本中将字符串转换为日期

问题描述:

我是GAS的新手(实际上也是编码的新手) 我得到了一个日期字符串,格式为yyyymmdd(例如20140807),如何将其转换为日期,以便Google Apps脚本可以识别它,以后我可以进行一些计算(主要是与var today = new Date();中的Today进行比较)

I am new to GAS (actually new to coding too) I got a date string in the format of yyyymmdd (eg. 20140807), how could I turn it to date so that Google apps script can recognize it and later I can do some calculation (mostly to compare with Today as in var today = new Date();)

Google Apps脚本无法正确识别以下内容:

Google apps script can't recognize the following correctly:

// string is in the format of yyyymmdd (eg. 20140807)
var pubdate = new Date(string)

唯一方法-手动解析字符串 :

The only way - parse the string by hand:

var dateStr = "20140807"

var year = +dateStr.substring(0, 4)
var month = +dateStr.substring(4, 6)
var day = +dateStr.substring(6, 8)

var pubdate = new Date(year, month - 1, day)

month - 1的原因是月份的编号从0开始.

函数前的+符号只是将函数返回的字符串转换为数字,因此我们可以将它们直接传递到new Date()

And the + sign before function just converts string, which is returned by functions, to numbers so we can pass them right into new Date()