javascript 没有时间的Javascript日期方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26528085/
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 06:05:14  来源:igfitidea点击:

Javascript date method without time

javascriptdate

提问by Pogrindis

Javascript method

Javascript 方法

var d = new Date();

get datetime value, but how get clear date, without time ?

获得日期时间值,但如何在没有时间的情况下获得明确的日期?

回答by Pogrindis

There are so many examples of this..

这方面的例子太多了。。

function format(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

var today = new Date();
var dateString = format(today);
alert(dateString);

I also like to point out whenever dealing with time.. MomentJS really is the perfect tool for the job

我也想在处理时间的时候指出.. MomentJS 真的是这个工作的完美工具

MomentJS

MomentJS

another super simple example...

另一个超级简单的例子......

var today = new Date();
alert(today.toLocaleDateString());

second example is my favourite.

第二个例子是我最喜欢的。

回答by Mica?l Félix

I would advise you to use momentjs(http://momentjs.com/) for all your javascript problems concerning dates.

我建议您使用momentjs( http://momentjs.com/) 来解决有关日期的所有 javascript 问题。

This code will reset hours, minutes, seconds, milliseconds of your javascript date object.

此代码将重置您的 javascript 日期对象的小时、分钟、秒、毫秒。

var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);

Without conversion, and you still have a date object at the end.

没有转换,最后你仍然有一个日期对象。

回答by Waqas Ahmed

For complete reference of parsing date Follow link here

有关解析日期的完整参考,请点击此处的链接

You can simply parse only date from you variable like

您可以简单地仅解析来自变量的日期,例如

d.toJSON().substring(0,10)

or

或者

d.toDateString();

回答by fboes

With Dateyou have a date object, which has several methods. A complete list of methods can be found in the Javascript Date object documentation.

Date你有个约会对象,其中有几种方法。完整的方法列表可以在Javascript 日期对象文档中找到

In your case:

在你的情况下:

var d = new Date(),
    datestring = '';

datestring = d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate()

alert(datestring);

回答by CSquared

Depending on what format you like, I think these are the easiest ways to get just the date without the time.

根据您喜欢的格式,我认为这些是获取没有时间的日期的最简单方法。

new Date().toJSON().split("T")[0];
// Output: "2019-10-04"

or

或者

new Date().toLocaleDateString().split(",")[0]
// Output in the US: "10/4/2019"

回答by Дмитрий Дорогонов

new Intl.DateTimeFormat('en-GB').format(new Date('2018-08-17T21:00:00.000Z'))

new Intl.DateTimeFormat('en-GB').format(new Date('2018-08-17T21:00:00.000Z'))

The result will be: 18/08/2018

结果将是:18/08/2018

You can check the descriptionhere.

您可以在此处查看说明