简体   繁体   English

如何将DateTime字符串格式转换为其他DateTime?

[英]How can I cast a DateTime string format to other DateTime?

I have a string that is: Thu, 16 May 2019 08:45:15 GMT and I need to cast it to two strings: 16/05/2019 and 08:45:15 . 我有一个字符串,是: Thu, 16 May 2019 08:45:15 GMT我需要将其转换为两个字符串: 16/05/201908:45:15

I have tryed many ways (I have seen other post of StackOverFlow) but I did not achieve that. 我尝试了很多方法(我已经看过StackOverFlow的其他文章),但是我没有实现。

How could I do that? 我该怎么办?

EDIT 1: 编辑1:

I have tryed, for example, this code: 我尝试过例如以下代码:

console.log(
  new Intl.DateTimeFormat(
    'en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }
  ).format("Thu, 16 May 2019 08:45:15 GMT"))

The problem is all examples I see are from Date.now() (typeof Datetime) not a custom string like mine 问题是我看到的所有示例都来自Date.now() (typeof Datetime),而不是像我这样的自定义字符串

You just need to convert that string 您只需要转换该字符串

note: Since you are using GMT time, you'll want to call the .getUTC* function names 注意:由于您使用的是格林尼治标准时间,因此您需要调用.getUTC*函数名称

Also note that months are zero-indexed, so you'll need to add one to that. 还要注意,月份是零索引的,因此您需要在其中加一个。

 var d = new Date("Thu, 16 May 2019 08:45:15 GMT"); var dateStr = d.getUTCDate() + '/' + (d.getUTCMonth() + 1) + '/' + d.getUTCFullYear(); var timeStr = d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds(); console.log(dateStr); console.log(timeStr); 

or given your example using Intl.DateTimeFormat you can just add a new Date() object in there (instead of a plain string) and you're good to go. 或使用Intl.DateTimeFormat给定您的示例,您只需在其中添加一个new Date()对象(而不是纯字符串)就可以了。

 var d = new Date("Thu, 16 May 2019 08:45:15 GMT"); var formatted = Intl.DateTimeFormat( 'en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(d); console.log(formatted); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM