Kayote
Kayote

Reputation: 15617

Get & Set Time from Date Object

I am working on a pomodoro clock in Javascript.

I am a bit confused by the Date Obj. As per the below code, the idea is that the 'Session Timer' & 'Break Timer' values will be stored in a global obj so they can be retrieved &/ or updated. However, the following is confusing me:

// The following stores the current time
// which makes sense.
const meter = {
    break : new Date(),
    session : new Date()
};
// However, when I set the minutes on the Date obj
// the above break & session props are no longer
// a Date obj, instead they are number.
// So, I cant use the 'getMinutes()'
const meter = {
    break : new Date().setMinutes( 5 ), // is a number, not Date anymore!
    session : new Date().setMinutes( 10 ) // is a number, not Date anymore!
};

I could pass the break / session numbers through new Date() method to create a new date but I wonder how would I create the timer (mainly in format [hr]:[min]:[sec]). Would I have to do something as follows every second before I update the code:

let number = 1470650701308; // time in milliseconds as returned by methods (getMinutes(), getHours(), getSeconds())
let hours = 1470650701308 / ( 1000 * 60 * 60 ); // ms * sec * min 
let minutes = 1470650701308 / ( 1000 * 60 ); // ms * sec
let seconds = 1470650701308 / ( 1000 ); // ms

So my question is how to go about getting the time in hours / minutes & seconds so I can update my clock every second?

Thanks

Upvotes: 0

Views: 154

Answers (1)

Bart van den Burg
Bart van den Burg

Reputation: 2344

The setminutes method modifies the object and returns an int.

try this instead:

const meter = {
    break : new Date(),
    session : new Date()
};

meter.break.setMinutes(5);
meter.session.setMinutes(10);

Upvotes: 0

Related Questions