在JavaScript中获取当前日期和时间

662

我有一个 JavaScript 脚本,可以打印当前的日期和时间,但是DATE总是错误的。以下是代码:

var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth() 
+ "/" + currentdate.getFullYear() + " @ " 
+ currentdate.getHours() + ":" 
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();

它应该打印18/04/2012 15:07:33,但实际输出3/3/2012 15:07:33


15
通常,您应该努力阅读正在使用的API的文档。这里是一些有关JavaScript日期对象的文档:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date。您需要了解的所有内容都可以在那里找到,以解决您的问题。 - Steven Oxley
3
可能是如何在JavaScript中获取当前日期的重复问题。 - Jon
我认为JavaScript将从系统获取当前日期和时间。因此,请在计算机上设置当前日期和时间。 - Billy
这是2012年第3个月(从0开始计数),星期三(从星期日开始,也是从0开始计数)。 - SparK
13
人们经常抱怨某些问题,但是在SO上几乎没有问题是不能通过阅读文档来回答的。我喜欢这个网站,因为它提供了简洁的答案以及如何完成我正在尝试做的事情的示例,就像这个问题所做的那样。 - Chris Sharp
19
当人们在谷歌搜索时,他们会来到这里而不是API文档,分享知识而不让人感到难过,这样真的很糟糕吗? - Mauricio Gracia Gutierrez
35个回答

5
getDay() 获取星期几,其中 3 表示星期三。你需要使用 getDate(),它会返回 18
此外,getMonth()0 开始计数,所以需要加上 1 才能得到 4(四月)。
演示: http://jsfiddle.net/4zVxp/

5
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time 
console.log(date.toLocaleString()) // For both Date and Time 

点击查看文档


5

您需要使用getDate()函数获取日期部分。getDay()函数返回星期几的数字(周日=0,周一=1...),而getMonth()返回一个基于0的索引,因此您需要将其加1。

 var currentdate = new Date(); 

 var datetime = "Last Sync: " + currentdate.getDate() + "/"+  (parseInt(currentdate.getMonth())    + 1)
   + "/" + currentdate.getFullYear() + " @ "  
   + currentdate.getHours() + ":"  
   + currentdate.getMinutes() + ":" + currentdate.getSeconds(); 

5

通过使用默认的Date()

const now = new Date();
console.log(now); // Output: Thu Sep 23 2021 13:24:52 GMT-0400 (Eastern Daylight Time)

对于不同的日期和时间格式,您可以使用toLocaleString()

短日期格式: MM/DD/YYYY
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { dateStyle: 'short' });
console.log(formattedDate);
// 输出: "9/23/2021"

长日期格式: Weekday, Month Day, Year
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log(formattedDate);
// 输出: "Thursday, September 23, 2021"

短时间格式: HH:MM AM/PM
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { timeStyle: 'short' });
console.log(formattedDate);
// 输出: "1:24 PM"

长时间格式: HH:MM:SS AM/PM Timezone
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true, timeZoneName: 'short' });
console.log(formattedDate);
// 输出: "1:24:52 PM EDT"


ISO 8601 格式: YYYY-MM-DDTHH:MM:SSZ
const now = new Date();
const isoDate = now.toISOString();
console.log(isoDate);
// 输出: "2021-09-23T17:24:52.740Z"

3

这个问题很久以前就有了,而且答案也太过复杂了。现在我们可以使用moment.js来获取当前日期,这实际上使得它非常容易。所有需要做的就是在我们的项目中包含moment.js,然后获得格式化良好的日期,例如:

moment().format("dddd, MMMM Do YYYY, h:mm:ss a");

我认为这样可以更轻松地处理javascript中的日期。


3
获取当前日期和时间
var now = new Date(); 
  var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate(); 
  datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds(); 

3
function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

2

.getDay 返回一周中的该天。你需要使用 .getDate 来替代。 .getMonth 返回值从0到11。你需要将结果加1才能得到“人类”月份。


2

这段小代码易于使用且适用于任何地方。

<p id="dnt"></p>
<script>
document.getElementById("dnt").innerHTML = Date();
</script>

还有设计的空间


2
function UniqueDateTime(format='',language='en-US'){
    //returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
    //e.g : 20170428-115833-547
    //allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
    var dt = new Date();
    var modele="YYYYMMDD-HHmmSS-mss";
    if (format!==''){
      modele=format;
    }
    modele=modele.replace("YYYY",dt.getFullYear());
    modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
    modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
    modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
    modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
    modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
    modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
    return modele;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接