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

I have found the simplest way to get current date and time in JavaScript from here - 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;
查看更多
呛了眼睛熬了心
3楼-- · 2019-01-02 19:50

This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:

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

I think that makes it way easier to handle dates in javascript.

查看更多
忆尘夕之涩
4楼-- · 2019-01-02 19:50

My well intended answer is to use this tiny bit of 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
查看更多
后来的你喜欢了谁
5楼-- · 2019-01-02 19:51

When calling .getMonth() you need to add +1 to display the correct month. Javascript count always starts at 0 (look here to check why), so calling .getMonth() in may will return 4 and not 5.

So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:

  • .getDate() returns the day of the month <- this is the one you want
  • .getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc

so your code should look like this:

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

JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances

You can make use of the prototype constructor for the Date object and create a new method of the Date object to return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.

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

You can then simply retrieve the date and time by doing the following:

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

Or call the method inline so it would simply be -

var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();
查看更多
何处买醉
6楼-- · 2019-01-02 19:51

.getDay returns day of week. You need .getDate instead. .getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.

查看更多
梦该遗忘
7楼-- · 2019-01-02 19:51

Basic JS (good to learn): we use the Date() function and do all that we need to show the date and day in our custom format.

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 & easy): Install the npm pagckage using (npm install date-and-time), then run the below.

let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
查看更多
登录 后发表回答