从Java格式的时间戳记中获取“日期”

时间:2019-06-10 16:56:02

标签: javascript timestamp

我正在Google Sheets中使用Javascript,但在转换或解析格式化的时间戳时遇到了麻烦,最终无法将日期提取为数值。

我的代码:

var shopifyTimestamp = "2019-05-18 13:21:17 +0100";

var date = new Date(shopifyTimestamp);

Logger.log(date.getDay());

输出:

[19-06-10 17:40:56:107 BST] NaN

我的目标是从该时间戳记中提取天数,例如“ 18”。

但是,它似乎没有将其转换。我怀疑我的时间戳记对于date()函数的格式不正确,所以它与创建一个函数进行解析有关。

希望您可以帮助我! :) 非常感谢。

3 个答案:

答案 0 :(得分:0)

date对象具有这样的方法,用于将月份中的日期作为数字(1-31)。

date.getDate();

答案 1 :(得分:0)

18是日期。

var shopifyTimestamp ="2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);

console.log(date.getDate());

答案 2 :(得分:0)

JavaScript的Date构造函数支持ISO 8601 date strings。无需使用任何库,您可以执行以下操作:

var shopifyTimestamp = "2019-05-18 13:21:17 +0100";

// will produce `2019-05-18T13:21:17+0100`
var isoDate = shopifyTimestamp.slice(0, 10)
    + 'T' + shopifyTimestamp.slice(11, 19)
    + shopifyTimestamp.slice(20);

var date = new Date(isoDate);

console.log(date.getDate()); // 18

还要注意,您正在寻找的是date.getDate(),而不是date.getDay()。后者返回星期的数字日期。

相关问题