首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将字符串日期格式`10月18日2019`转换为有效日期`2019-10-17T23:00:00.000Z`

如何将字符串日期格式`10月18日2019`转换为有效日期`2019-10-17T23:00:00.000Z`
EN

Stack Overflow用户
提问于 2019-11-11 20:57:56
回答 1查看 187关注 0票数 0

我需要将像这样的字符串日期格式('MMMM Do YYYY')转换为有效的日期2019-10-17T23:00:00.000Z或类似的17/10/2019

我曾尝试使用将字符串解析为moment,但一直收到错误

更新:我使用的是moment('October 18th 2019').format()。接收到无效的日期作为错误,很抱歉我应该澄清我正在尝试将字符串October 18th 2019转换为有效的日期格式,

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-13 02:14:54

您只需在构造Moment对象时为输入(MMMM Do YYYY)提供格式字符串,使用以下方法之一:

代码语言:javascript
复制
// this way interprets the input at the start of the day in the local time zone
moment('October 18th 2019', 'MMMM Do YYYY')

// this way interprets the input at the start of the day in UTC
moment.utc('October 18th 2019', 'MMMM Do YYYY')

// this way interprets the input at the start of the day in a specific named time zone
// (requires the moment-timezone add-on)
moment.tz('October 18th 2019', 'MMMM Do YYYY', 'Europe/London')

然后,您可以根据需要对其进行格式化和/或转换。例如:

代码语言:javascript
复制
// this way keeps the local time, includes the local time offset when formatting
moment('October 18th 2019', 'MMMM Do YYYY').format()

// this way converts from local to utc before formatting
moment('October 18th 2019', 'MMMM Do YYYY').utc().format()

// this way converts from local to utc before formatting and includes milliseconds
moment('October 18th 2019', 'MMMM Do YYYY').toISOString()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58801846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档