Exe
Exe

Reputation: 11

How can i update the date? it gets stuck on the date when i ran the app

I want to update the Date each day, right now it gets stuck on the Date when i opened the app, when i open it says for example: Sunday 22 February 2015, and tomorrow it will keep showing Sunday 22 February 2015 instead of Monday 23 February 2015.

The JQuery Code:

$(document).ready(function() {
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; 
var dayNames["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var newDate = new Date();

newDate.setDate(newDate.getDate());

$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());

setInterval( function() {
var seconds = new Date().getSeconds();
$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
},1000);

setInterval( function() {
var minutes = new Date().getMinutes();
$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
},1000);

setInterval( function() {
var hours = new Date().getHours();
$("#hours").html(( hours < 10 ? "0" : "" ) + hours);
}, 1000);
}); 

to load on:

<div id="Date"></div>
<div id="hours"></div>
<div id="min"></div>
<div id="sec"></div>

working Demo

Upvotes: 1

Views: 67

Answers (2)

Jeremy Thille
Jeremy Thille

Reputation: 26390

Use Moment.js and write something like moment().format('MMMM Do YYYY, h:mm:ss a'); or moment().format('LLLL') that will give you Sunday, February 22, 2015 6:11 PM, updated in real time.

Moment was especially written to avoid developers messing up with dates and pulling their hair out.

In case you can't or don't want to use Moment, do as Miro said (at least don't set 3 intervals when one is enough :)

Upvotes: 1

Miro
Miro

Reputation: 8650

First, you don't need 3 different intervals.

Just put the date inside the interval and you'll be set. Here you go:

http://jsfiddle.net/mirohristov/679wjmkm/2/

setInterval( function() {
    var seconds = new Date().getSeconds();
    $("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
        var minutes = new Date().getMinutes();
    $("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
        var hours = new Date().getHours();
    $("#hours").html(( hours < 10 ? "0" : "" ) + hours);
    var date = newDate.setDate(newDate.getDate());
    $('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
    },1000);
});

Upvotes: 1

Related Questions