577

我有一个在 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

4

31 回答 31

703

.getMonth()返回一个从零开始的数字,因此要获得正确的月份,您需要加 1,因此调用.getMonth()may 将返回4而不是5

因此,在您的代码中,我们可以使用它currentdate.getMonth()+1来输出正确的值。此外:

  • .getDate()返回月份中的哪一天<- 这是你想要的那一天
  • .getDay()Date对象的一个​​单独方法,它将返回一个表示当前星期几的整数 (0-6)0 == Sunday

所以你的代码应该是这样的:

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

JavaScript Date 实例继承自 Date.prototype。您可以修改构造函数的原型对象以影响 JavaScript Date 实例继承的属性和方法

您可以使用Date原型对象创建一个新方法,该方法将返回今天的日期和时间。这些新方法或属性将被Date对象的所有实例继承,因此如果您需要重用此功能,它特别有用。

// For todays date;
Date.prototype.today = function () { 
    return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}

// For the time now
Date.prototype.timeNow = function () {
     return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}

然后,您可以通过执行以下操作简单地检索日期和时间:

var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();

或者调用内联方法,这样它就可以简单地 -

var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();
于 2012-04-18T14:11:58.877 回答
407

要获取时间和日期,您应该使用

    new Date().toLocaleString();

>> "09/08/2014, 2:35:56 AM"

仅获取您应该使用的日期

    new Date().toLocaleDateString();

>> "09/08/2014"

只得到你应该使用的时间

    new Date().toLocaleTimeString();

>> "2:35:56 AM"

或者,如果您只想要hh:mm美国英语没有 AM/PM格式的时间

    new Date().toLocaleTimeString('en-US', { hour12: false, 
                                             hour: "numeric", 
                                             minute: "numeric"});
>> "02:35"

或英式英语

    new Date().toLocaleTimeString('en-GB', { hour: "numeric", 
                                             minute: "numeric"});

>> "02:35"

在这里阅读更多。

于 2015-05-14T19:39:47.130 回答
80

对于真正的 mysql 样式输出,请使用以下函数: 2019/02/28 15:33:12

  • 如果您单击下面的“运行代码片段”按钮
  • 它将向您展示一个简单的实时数字时钟示例
  • 该演示将出现在代码片段下方。

function getDateTime() {
        var now     = new Date(); 
        var year    = now.getFullYear();
        var month   = now.getMonth()+1; 
        var day     = now.getDate();
        var hour    = now.getHours();
        var minute  = now.getMinutes();
        var second  = now.getSeconds(); 
        if(month.toString().length == 1) {
             month = '0'+month;
        }
        if(day.toString().length == 1) {
             day = '0'+day;
        }   
        if(hour.toString().length == 1) {
             hour = '0'+hour;
        }
        if(minute.toString().length == 1) {
             minute = '0'+minute;
        }
        if(second.toString().length == 1) {
             second = '0'+second;
        }   
        var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   
         return dateTime;
    }

    // example usage: realtime clock
    setInterval(function(){
        currentTime = getDateTime();
        document.getElementById("digital-clock").innerHTML = currentTime;
    }, 1000);
<div id="digital-clock"></div>

于 2013-10-04T07:54:41.497 回答
35

只需使用:

var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
于 2015-01-31T19:55:14.347 回答
17

最短的

我开发了史蒂夫的答案以得到 OP 所需要的

new Date().toLocaleString().replace(',','')

console.log(new Date().toLocaleString().replace(',',''));

于 2020-08-03T13:00:32.037 回答
14
var currentdate = new Date();

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

.getDay()将方法更改为.GetDate()并在月份中添加一,因为它从 0 开始计算月份。

于 2012-04-18T14:11:52.300 回答
8

这应该可以解决问题:

function dateToString(date) {
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
    dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
    dateOfString += date.getFullYear();
    return dateOfString;
}

var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
            + currentdate.getMinutes() + ":"
            + currentdate.getSeconds();
于 2012-04-18T14:13:03.253 回答
7

基本 JS(好学):我们使用 Date() 函数并完成我们需要以自定义格式显示日期和日期的所有操作。

var myDate = new Date();

let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec'];


let date = myDate.getDate();
let month = monthsList[myDate.getMonth()];
let year = myDate.getFullYear();
let day = daysList[myDate.getDay()];

let today = `${date} ${month} ${year}, ${day}`;

let amOrPm;
let twelveHours = function (){
    if(myDate.getHours() > 12)
    {
        amOrPm = 'PM';
        let twentyFourHourTime = myDate.getHours();
        let conversion = twentyFourHourTime - 12;
        return `${conversion}`

    }else {
        amOrPm = 'AM';
        return `${myDate.getHours()}`}
};
let hours = twelveHours();
let minutes = myDate.getMinutes();

let currentTime = `${hours}:${minutes} ${amOrPm}`;

console.log(today + ' ' + currentTime);


Node JS(快速简单):使用( npm install date-and-time )安装 npm pagckage ,然后运行以下命令。

let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
于 2018-05-20T15:14:57.463 回答
6

我找到了从这里获取 JavaScript 中当前日期和时间的最简单方法 - How to get current Date and Time using JavaScript

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;
于 2016-04-21T07:02:02.077 回答
5

getDay()获取星期几。 3是星期三。你想要getDate(),那会回来18的。

也是getMonth()从 开始0,需要加到14四月)。

演示:http: //jsfiddle.net/4zVxp/

于 2012-04-18T14:12:37.613 回答
5

您需要使用 getDate() 来获取日期部分。getDay() 函数返回天数(Sunday = 0, Monday = 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(); 
于 2012-04-18T14:15:00.147 回答
4
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time 
console.log(date.toLocaleString()) // For both Date and Time 

对于文档

于 2021-09-21T03:35:29.700 回答
3

获取当前日期和时间

var now = new Date(); 
  var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate(); 
  datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds(); 
于 2013-07-25T11:17:40.633 回答
3

这个问题很老了,答案也很老。我们现在可以使用 moment.js 来获取当前日期,而不是那些可怕的函数,这实际上非常容易。所要做的就是在我们的项目中包含moment.js并获得格式正确的日期,例如,通过:

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

我认为这使得在 javascript 中处理日期变得更加容易。

于 2014-12-19T02:20:43.140 回答
2

.getDay 返回星期几。你需要 .getDate 代替。.getMonth 返回从 0 到 11 的值。您需要在结果中加 1 以获得“人类”月份数。

于 2012-04-18T14:14:51.150 回答
2
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())));
}
于 2013-03-22T09:44:20.847 回答
2

这个小代码很简单,可以在任何地方使用。

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

有设计空间

于 2014-12-15T18:06:24.203 回答
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;
}
于 2017-04-28T15:01:02.403 回答
1
var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);
于 2016-06-15T04:00:04.083 回答
1

我想我很晚才分享我的答案,但我认为这是值得的。

function __getCurrentDateTime(format){
    var dt=new Date(),x,date=[];
    date['d']=dt.getDate();
    date['dd']=dt.getDate()>10?dt.getDate():'0'+dt.getDate();
    date['m']=dt.getMonth()+1;
    date['mm']=(dt.getMonth()+1)>10?(dt.getMonth()+1):'0'+(dt.getMonth()+1);
    date['yyyy']=dt.getFullYear();
    date['yy']=dt.getFullYear().toString().slice(-2);
    date['h']=(dt.getHours()>12?dt.getHours()-12:dt.getHours());
    date['hh']=dt.getHours();
    date['mi']=dt.getMinutes();
    date['mimi']=dt.getMinutes()<10?('0'+dt.getMinutes()):dt.getMinutes();
    date['s']=dt.getSeconds();
    date['ss']=dt.getSeconds()<10?('0'+dt.getSeconds()):dt.getSeconds();
    date['sss']=dt.getMilliseconds();
    date['ampm']=(dt.getHours()>=12?'PM':'AM');
    x=format.toLowerCase();
    x=x.indexOf('dd')!=-1?x.replace(/(dd)/i,date['dd']):x.replace(/(d)/i,date['d']);
    x=x.indexOf('mm')!=-1?x.replace(/(mm)/i,date['mm']):x.replace(/(m)/i,date['m']);
    x=x.indexOf('yyyy')!=-1?x.replace(/(yyyy)/i,date['yyyy']):x.replace(/(yy)/i,date['yy']);
    x=x.indexOf('hh')!=-1?x.replace(/(hh)/i,date['hh']):x.replace(/(h)/i,date['h']);
    x=x.indexOf('mimi')!=-1?x.replace(/(mimi)/i,date['mimi']):x.replace(/(mi)/i,date['mi']);
    if(x.indexOf('sss')!=-1){   x=x.replace(/(sss)/i,date['sss']);  }
    x=x.indexOf('ss')!=-1?x.replace(/(ss)/i,date['ss']):x.replace(/(s)/i,date['s']);
    if(x.indexOf('ampm')!=-1){  x=x.replace(/(ampm)/i,date['ampm']);    }
    return x;
}

console.log(__getCurrentDateTime());  //returns in dd-mm-yyyy HH:MM:SS
console.log(__getCurrentDateTime('dd-mm-yyyy'));    //return in 05-12-2016
console.log(__getCurrentDateTime('dd/mm*yyyy'));    //return in 05/12*2016
console.log(__getCurrentDateTime('hh:mimi:ss'));    //return in 13:05:30

console.log(__getCurrentDateTime('h:mi:ss ampm')); //在下午 1:5:30 返回

于 2016-12-05T13:51:45.260 回答
1

我需要弄清楚这一点,以备后效。这是我从几个不同来源获取元素后得出的结果——格式为 MM/DD/YYYY HH:MM AM/PM

D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();

N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}

amtOfZeroes = 2;
isNeg = false;

if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{

Mo = "0" + Mo; 
}
if (isNeg)
Mo = "-" + Mo;

if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho; 
}
if (isNeg)
Ho = "-" + Ho;

if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min; 
}
if (isNeg)
Min = "-" + Min;

T = Ho + ":" + (Min)

Mo + "/" + D.getDate() + "/" + D.getFullYear() + "  " + T + " " + N
于 2017-05-17T18:51:31.807 回答
0
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" + 
dt.toISOString().substring(5,7)+ "/" + 
dt.toISOString().substring(0,4) + " " + 
dt.toTimeString().substring(0,8))
于 2014-08-07T18:19:18.040 回答
0
function display_c(){   
    var refresh = 1000; // Refresh rate in milli seconds    
    mytime = setTimeout('display_ct()', refresh)    
}

function display_ct() {

    var strcount    
    var currentdate = new Date();

    document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();

    tt = display_c();   
}


id = 'ct'     // Replace in Your id

onload = "display_ct();"     // Type inside a Body Tag
于 2015-12-22T09:10:34.870 回答
0

我精心准备的答案是使用这一点点 JS:https ://github.com/rhroyston/clock-js

clock.now   --> 1462248501241
clock.time  --> 11:08 PM
clock.weekday   --> monday
clock.day   --> 2
clock.month --> may
clock.year  --> 2016
clock.since(1462245888784)  --> 44 minutes
clock.until(1462255888784)  --> 2 hours
clock.what.time(1462245888784)  --> 10:24 PM
clock.what.weekday(1461968554458)   --> friday
clock.what.day('14622458887 84')    --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458')    --> 2016
clock.what.time()   --> 11:11 PM
clock.what.weekday('14619685abcd')  -->     clock.js error : expected unix timestamp as argument
clock.unit.seconds  --> 1000
clock.unit.minutes  --> 60000
clock.unit.hours    --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks    --> 604800000
clock.unit.months   --> 2628002880
clock.unit.years    --> 31536000000
于 2016-05-03T22:02:11.037 回答
0

它简单而精湛

 $(document).ready(function () { 
            var fpsOut = document.getElementById('myTime');
            setInterval(function () {
                var d = new Date(); 
                fpsOut.innerHTML = d;
            }, 1000);
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTime"></div>

请找到下面的提琴手的例子

http://jsfiddle.net/4zVxp/483/

于 2017-09-11T07:15:57.680 回答
0

如果有人在寻找功能

console.log(formatAMPM());
function formatAMPM() {
  var date = new Date();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  return strTime = date.getMonth() + '/' + date.getDay()+'/'+date.getFullYear()+' '+ hours + ':' + minutes +':'+ seconds + " " +ampm;
}
于 2019-03-27T08:48:43.077 回答
0

这是我全天候工作的完整格式,包含日期、日期、年份和时间,并确保您的 PC 的日期设置为正确的日期,如果您使用的是 PHP,请确保在 php.ini date.timezone=xx where xx your当前时区

function startTime()
{
    var today=new Date();
    //                   1    2    3    4    5    6    7    8    9   10    11  12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33
    var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st','nd','rd'];

    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";

    var month = new Array(12);
    month[0] = "January";
    month[1] = "February";
    month[2] = "March";
    month[3] = "April";
    month[4] = "May";
    month[5] = "June";
    month[6] = "July";
    month[7] = "August";
    month[8] = "September";
    month[9] = "October";
    month[10] = "November";
    month[11] = "December";

    document.getElementById('txt').innerHTML=(weekday[today.getDay()] + ',' + " " + today.getDate()+'<sup>'+suffixes[today.getDate()]+'</sup>' + ' of' + " " + month[today.getMonth()] + " " + today.getFullYear() + ' Time Now ' + today.toLocaleTimeString());
    t=setTimeout(function(){startTime()},500);
}
<style>
sup {
        vertical-align: super;
        font-size: smaller;
    }
</style>
<html>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

于 2021-01-24T13:25:01.903 回答
0

这个英国时区的例子.. offset为特定的时区设置。示例:印度:+05:30,英国:+1

 function realUKTime() {
        // create Date object for current location
        var d = new Date();
        offset ='+1';
       
        // convert to msec
        // subtract local time zone offset
        // get UTC time in msec
        var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

        // create new Date object for different city
        // using supplied offset
        var nd = new Date(utc + (3600000*offset));

        // return time as a string
        var s = nd.getSeconds();
        var i = nd.getMinutes();
        var h = nd.getHours();
        var cDate =  nd.getDate();
        var m =  nd.getUTCMonth();
        var y = nd.getFullYear();

       var newUkTime = nd.toDateString() + " "+ (Number(h)-1)+":"+i+':'+s
        $("#realTime").html(newUkTime);

    }

    setInterval(realUKTime(),1000);

输出:: 2021 年 12 月 27 日星期一 12:6:3

于 2021-12-27T12:05:40.057 回答
0

简短而简单:-

console.log(new Date().toLocaleString());

参考

于 2022-02-12T05:12:17.677 回答
-2

看看这个可能对你有用

<script language="JavaScript">
var dayarray=new Array("Sunday","Monday",
 "Tuesday","Wednesday","Thursday","Friday","Saturday")

var montharray=new Array("January","February","March",
 "April","May","June","July","August","September",
 "October","November","December")

function getthedate(){
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="AM"
if (hours>=12)
dn="PM"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//change font size here
var cdate="<small><font color='000000' face='Arial'><b>"+dayarray[day]+", 
    "+montharray[month]+" "+daym+", "+year+" "+hours+":"
 +minutes+":"+seconds+" "+dn
    +"</b></font></small>"
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
 if (!document.all&&!document.getElementById)
  getthedate()
  function goforit(){
  if (document.all||document.getElementById)
 setInterval("getthedate()",1000)
}

 </script>

enter code here

 <span id="clock"></span>
于 2013-04-12T15:26:11.523 回答
-4

<p id="DateTimeBox">Click The Button To Show Date And Time</p>
<button onclick="ShowDate();"> Show Date </button>
<script>
  function ShowDate() {
    document.getElementById('DateTimeBox').innerHTML = Date();
  }
</script>

于 2018-01-10T21:03:27.317 回答