在 Javascript 中获取今天的日期

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

Get todays date in Javascript

javascript

提问by slandau

How can I get the current date in Javascript in this format?

如何以这种格式在 Javascript 中获取当前日期?

"M/D/YYYY"?

“月/日/YYYY”?

Thanks.

谢谢。

If this would be today it would be

如果是今天,那就是

"2/17/2011", if it was the 3rd it would be "2/3/2011".

“2/17/2011”,如果是第三个,那就是“2/3/2011”。

Thanks

谢谢

回答by The Muffin Man

var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)

I assigned each part into its own variable for this example so that it's more clear as to what it returns.

对于这个例子,我将每个部分分配到自己的变量中,以便更清楚地了解它返回的内容。

回答by Chris Baker

Use the javascript Dateobject:

使用 javascriptDate对象:

var d = new Date();
alert((d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear());

回答by RichMeister

Steven Levithan's (stevenlevithan.com) dateFormat function looks really versatile to me.

Steven Levithan (stevenlevithan.com) 的 dateFormat 函数对我来说看起来非常通用。

See:

看:

http://blog.stevenlevithan.com/archives/date-time-format

http://blog.stevenlevithan.com/archives/date-time-format

In his code, he adds dateFormat in as a prototype method for Date.

在他的代码中,他添加了 dateFormat 作为 Date 的原型方法。

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

So you can use it as a method on a Date object.

因此,您可以将其用作 Date 对象的方法。

var now = new Date();

var variable=now.format("m/dd/yy");

document.write(variable);

HTH

HTH

Rich

富有的