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

时间:2012-04-18 14:08:44

标签: javascript string date time concatenation

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

有任何帮助吗?感谢

29 个答案:

答案 0 :(得分:528)

致电.getMonth()时,您需要添加+1才能显示正确的月份。 Javascript的计数始终从0开始,因此调用.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();

答案 1 :(得分:211)

要获得时间和日期,请使用

    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"

了解更多here

答案 2 :(得分:61)

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

  • 如果您点击“运行代码段”&#39;
  • 下面的按钮
  • 它将显示一个简单的实时数字时钟示例
  • 该演示将显示在代码段下方。

&#13;
&#13;
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);
&#13;
<div id="digital-clock"></div>
&#13;
&#13;
&#13;     

答案 3 :(得分:27)

只需使用:

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

答案 4 :(得分:11)

var currentdate = new Date();

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

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

答案 5 :(得分:5)

这应该可以解决问题:

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();

答案 6 :(得分:4)

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

答案 7 :(得分:4)

getDay()获取一周中的某一天。 3是星期三。您需要getDate(),这将返回18

同样getMonth()0开始,您需要添加1才能获得4(4月)。

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

答案 8 :(得分:3)

获取当前日期和时间

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

答案 9 :(得分:3)

我找到了从这里获取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;

答案 10 :(得分:2)

.getDay返回星期几。你需要.getDate。 .getMonth返回0到11之间的值。您需要在结果中加1才能获得“人工”月份数。

答案 11 :(得分:2)

最短

我开发Steve answer来获得OP的确切需求

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

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

答案 12 :(得分: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

答案 13 :(得分:1)

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

答案 14 :(得分:1)

基本JS(好学):我们使用Date()函数,并以我们的自定义格式执行所有我们需要的日期和日期。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

节点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);

答案 15 :(得分:1)

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

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

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

答案 16 :(得分:1)

这个小代码很简单,无处不在。

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

有设计空间

答案 17 :(得分:1)

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

答案 18 :(得分: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;
}

答案 19 :(得分:0)

var now = new Date();

 var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

 var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

 var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();

 function fourdigits(number)    {
         return (number < 1000) ? number + 1900 : number;
                                                                 }
 today =  days[now.getDay()] + ", " +
          months[now.getMonth()] + " " +
          date + ", " +
          (fourdigits(now.getYear()))+" "
          + now.getHours()+":"+now.getMinutes() + ":"
          + now.getSeconds();

推荐http://anushitech.com/how/current-date-and-time-in-javascript

答案 20 :(得分:0)

它简单而精湛

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

请找到以下提琴手的例子

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

答案 21 :(得分: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

答案 22 :(得分:0)

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

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

答案 23 :(得分:0)

var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);

答案 24 :(得分: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

答案 25 :(得分: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))

答案 26 :(得分:-1)

检查出来可能会对你有用

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

答案 27 :(得分:-1)

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


void gerirFicheiros(string *equipa, int *nEquipas, membro medico[][50], int *nMedicos)
{

    // variaveis
    FILE *ficheiro;
    int i;

    // tentar abrir ficheiro (r = leitura b = binario)
    ficheiro = fopen(FICHEIRO_NEQUIPAS, "rb");

    // se não foi possivel abrir o ficheiro (por exemplo: por não existir), mostra erro e sai
    if (ficheiro == NULL)
    {
        printf("!!!não foi possivel abrir o ficheiro %s!!!\n", FICHEIRO_NEQUIPAS);
        return;
    }

    fread(nEquipas, sizeof(int), 1, ficheiro);

    // fechar o ficheiro
    fclose(ficheiro);

    ficheiro = fopen(FICHEIRO_EQUIPAS, "rb");
    
    // se não foi possivel abrir o ficheiro (por exemplo: por não existir), mostra erro e sai
    if (ficheiro == NULL)
    {
        printf("!!!não foi possivel abrir o ficheiro %s!!!\n", FICHEIRO_EQUIPAS);
        return;
    }
    
    // posicionar no inicio do ficheiro
    rewind(ficheiro);  

    
     fread(equipa, sizeof(string), *nEquipas, ficheiro);
    

    // fechar o ficheiro
    fclose(ficheiro);

}

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>

答案 28 :(得分:-3)

&#13;
&#13;
Spliterator
&#13;
&#13;
&#13;