javascript Javascript重新格式化日期字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28271904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:42:26  来源:igfitidea点击:

Javascript reformat date string

javascript

提问by Max Pain

I have this date fromat:

我有这个日期:

Mon Feb 02 2015 05:18:44 GMT+0000 (UTC) 

How can I reformat it to something more friendlier such as 2/2/2015I am using javascript.

我怎样才能将它重新格式化为更友好的东西,比如2/2/2015我正在使用 javascript。

I tried using .formatand dateFormatbut they both return undefined value.

我尝试使用.formatanddateFormat但它们都返回未定义的值。

How can I do this? I don't want to use any regex please.

我怎样才能做到这一点?我不想使用任何正则表达式。

回答by konkked

If you want the simplest way just concat all of the separate parts

如果您想要最简单的方法,只需连接所有单独的部分

var output = dt.getMonth( ) + 1 +'/'+ dt.getDate( ) + '/' +dt.getFullYear( );

There are a few libraries that will handle more advanced stuff if you need it, but that is the lightest way I can think of doing what you are asking.

如果您需要,有一些库可以处理更高级的东西,但这是我能想到的最轻松的方式来完成您的要求。

回答by Sameer Azazi

Use this awesome library. Moment JS

使用这个很棒的库。瞬间JS

For your case it would be some thing link

对于您的情况,这将是一些链接

var dateString = 'Mon Feb 02 2015 05:18:44 GMT+0000';
var date = new Moment(dateString);

alert(date.format('MM/dd/YYYY'));

回答by Kothari

var d = new Date(); var n = d.toLocaleDateString();

var d = new Date(); var n = d.toLocaleDateString();

I think this will give you desired output.

我认为这会给你想要的输出。

回答by omxian

You can pass it to DateObject:

您可以将其传递给Date对象:

var dateString = "Mon Feb 02 2015 05:18:44 GMT+0000 (UTC)";
var date = new Date(dateString);

date.getDate(); // > 2 (the day number)
date.getMonth(); // > 1 (the month number as 0 is January, 11 is December)

You can also find a lib to do the format job or format yourself.

您还可以找到一个库来完成格式化工作或自己格式化。

回答by cybersam

There are many ways to parse and re-format a date. Here is a very simple method that works for your date format:

有很多方法可以解析和重新格式化日期。这是一个适用于您的日期格式的非常简单的方法:

var d = 'Mon Feb 02 2015 05:18:44 GMT+0000 (UTC)';
var dStr = new Date(d).toDateString();

The value of dSTrwill be something like 'Sun Feb 01 2015'.

的值dSTr将类似于“Sun Feb 01 2015”。