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

我有一个脚本,打印当前的日期和时间在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:333/3/2012 15:07:33

1617275 次浏览
var currentdate = new Date();


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

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

.getMonth()返回一个从零开始的数字,所以为了得到正确的月份,你需要加1,所以在五月调用.getMonth()将返回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();

getDay()表示星期几。3是星期三。你想要getDate(),它将返回18

此外,getMonth()0开始,你需要添加1来获得4(四月)。

演示:# EYZ0

这应该可以达到目的:

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();
< p >。getDay返回星期几。你需要用. getdate代替。 . getmonth返回0到11的值。你需要在结果中加上1来得到“人类”月份数

您需要使用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();
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())));
}

看看这个也许会对你有用

<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>

获取当前日期和时间

var now = new Date();
var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();

对于真正的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>

dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" +
dt.toISOString().substring(5,7)+ "/" +
dt.toISOString().substring(0,4) + " " +
dt.toTimeString().substring(0,8))

这个小代码很简单,在任何地方都可以工作。

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

这里有设计的空间

这个问题很古老,答案也很古老。现在我们可以使用moment.js来获取当前日期,而不是那些怪异的函数,这实际上非常简单。所有要做的就是在我们的项目中包括<强> < em > moment.js < / em > < / >强,并获得一个格式良好的日期,例如,通过:

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

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

只使用:

var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");

来获得你应该使用的时间和日期

    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"

阅读更多在这里

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

我找到了最简单的方法来获得当前的日期和时间在JavaScript从这里- 如何获得当前的日期和时间使用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;

我精心设计的答案是使用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
var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);

我想现在分享我的答案已经很晚了,但我认为这是值得的。

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返回

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;
}

我需要在后期特效里弄清楚这一点。以下是我从几个不同的来源获取元素后得出的结论——格式是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

它简单而精湛

 $(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/

<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>

基本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 (quick &使用(NPM安装日期和时间)安装npm页面,然后运行下面的命令。

let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);

如果有人在寻找功能

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;
}

我开发了史蒂夫回答来得到OP需要的东西

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

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

这是我的工作围绕时钟完整格式的日期,日期,年份和时间 确保你的电脑的日期设置为正确的日期,如果你使用PHP,请确保在PHP .ini日期。Timezone = xx其中xx您当前的时区

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>

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

For Documentation

这个英国时区的例子。为特定的时区设置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

简单地说:-

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

Reference .

试试这个:

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;

输出:

2022-3-3 15:52:45