【问题标题】:Get current timestamp in NodeJS in DD-MM-YY-23:59:42 format以 DD-MM-YY-23:59:42 格式获取 NodeJS 中的当前时间戳
【发布时间】:2019-06-22 17:52:27
【问题描述】:

我在 AWS Lambda 中运行 NodeJS 8,并希望在函数运行时为当前日期、月份、年份和当前时间添加时间戳并将其附加到 S3。

因此,如果我的函数现在正在运行,它将输出 220619-183923(今天的日期和下午 6.39 和晚上 23 秒。)

对于像这样有点复杂的东西,我需要像 MomentJS 这样的东西还是可以用纯 Javascript 来完成?

最终这将构成一个 S3 URL,例如 https://s3.eu-west-2.amazonaws.com/mybucket.co.uk/BN-220619-183923.pdf

更新 Webhook 似乎有一些日期/时间数据,尽管格式略有不同,但未在 Lambda 函数中输出,因此这些数据在这里可能很有用。可以在 URL 中使用 ':' 吗?我假设以毫秒为单位的 UTC 可以转换成我想要的格式吗?

createdDatetime=2019-06-22T18%3A20%3A42%2B00%3A00&
date=1561231242&
date_utc=1561227642&

奇怪的是,date_utc 值实际上是实时数据。似乎在这里以 1970 年的形式出现?! https://currentmillis.com/

【问题讨论】:

  • 请看我的回答。我已经包含了查询参数。我的解决方案涵盖了 1970 年的事情。这是因为 AWS 缩短了 epoch。将三个零添加到时间戳的末尾,它将起作用。

标签: javascript node.js amazon-web-services aws-lambda momentjs


【解决方案1】:

创建这个日期字符串的目的是什么?如果您只需要它作为人类可读的时间戳,运行它就足够了:

new Date().toISOString()

这会为您提供服务器上的 UTC 时间。如果您需要时间始终处于特定时区,您可以使用 moment。

【讨论】:

  • 这会将日期输出为 YY-MM-DDThh:mm:ss.sssZ - OP 希望它为 DDMMYY-hhmmss
【解决方案2】:

你不需要时间。我提供了一个非常冗长但可以理解的解决方案。如果需要,可以将其短路。

由于您使用的是 S3,您还可以考虑使用每个日期函数的 UTC 版本(即,.getMonth() 变为 .getUTCMonth()

根据需要调整:

createdDatetime= new Date(decodeURIComponent('2019-06-22T18%3A20%3A42%2B00%3A00'))
date=new Date(1561231242 * 1000);
date_utc=new Date(1561227642 * 1000);

console.log(createdDatetime, date, date_utc)

const theDate = createdDatetime;
const day = theDate.getUTCDate();
const month = theDate.getUTCMonth()+1;
const twoDigitMonth = month<10? "0" + month: month;
const twoDigitYear = theDate.getUTCFullYear().toString().substr(2)
const hours = theDate.getUTCHours();
const mins = theDate.getUTCMinutes();
const seconds = theDate.getUTCSeconds();
const formattedDate = `${day}${twoDigitMonth}${twoDigitYear}-${hours}${mins}${seconds}`;

console.log(formattedDate);

根据您的更新进行更新:只要输入是 JavaScript Date 对象,此处的代码就可以工作。您提供的查询参数都可以用来创建Date对象。

【讨论】:

    【解决方案3】:

    您绝对可以使用 MomentJS 来实现这一点。如果你想避免使用大包,我使用这个实用函数来获得可读的格式,看看它是否有帮助

    https://gist.github.com/tstreamDOTh/b8b741853cc549f83e72572886f84479

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 2013-12-06
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 2013-06-04
      相关资源
      最近更新 更多