Getting current date and time in JavaScript

2019-01-02 18:53发布

I have a script that prints the current date and time in JavaScript, but the DATEis allways wrong. Here is the code:

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

It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33

Any help? Thanks

25条回答
栀子花@的思念
2楼-- · 2019-01-02 19:39

Just use:

var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
查看更多
泛滥B
3楼-- · 2019-01-02 19:39
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())));
}
查看更多
查无此人
4楼-- · 2019-01-02 19:43
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" + 
dt.toISOString().substring(5,7)+ "/" + 
dt.toISOString().substring(0,4) + " " + 
dt.toTimeString().substring(0,8))
查看更多
宁负流年不负卿
5楼-- · 2019-01-02 19:47

If you want true mysql style date time use this

2013/10/04 08:51:32

 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;
}
查看更多
长期被迫恋爱
6楼-- · 2019-01-02 19:47
var currentdate = new Date();

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

Change .getDay() method to .GetDate() and add one to month, because it counts months from 0.

查看更多
浅入江南
7楼-- · 2019-01-02 19:47

get current date and time

var now = new Date(); 
  var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate(); 
  datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds(); 
查看更多
登录 后发表回答