在Google Apps脚本中将字符串转换为日期 [英] Convert a string to date in google apps script

查看:77
本文介绍了在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()

这篇关于在Google Apps脚本中将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆