1

I have set up a function to get the current date and time in the format I want:

function date(){
        var d = new Date();
        var minutes = d.getMinutes();
        var month = d.getMonth() +1;
        if(minutes<10){
            return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + "0" + minutes);
        }else{
            return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + minutes);}
        }

I created an Object that takes the values (amount,date,type). How can I set it up so with every new instance of the object the date value be generated by the function date() automatically so that when it gets pushed to the array movements a timestamp is added?

Here is my code:

var movements =[];

//transactions
var initialBalance = new Transaction(1000,"date","cash");
var addIn = new Transaction(500,"date","cash");
var addOut = new Transaction(-300,"date","card");

//add the transactions to the movements array
movements.unshift(initialBalance);
movements.push(addIn);
movements.push(addOut);

I would like to do this with pure JS.

2
  • What is Transaction? Commented Oct 31, 2013 at 15:57
  • Do you simply need your Object's constructor to call the date() function and store it? Commented Oct 31, 2013 at 15:59

3 Answers 3

1

Maybe add the date function to the object

var Transaction = function(amount, type) {

    this.date = (function() {
        var d = new Date();
        var minutes = d.getMinutes();
        var month = d.getMonth() +1;
        if (minutes<10) {
            return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + "0" + minutes);
        } else {
            return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + minutes);
        }
    })();

    // now deal with amount and type...
}

The function will evaluate itself once you create the object.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems like a more sensible solution that the one I've offered.
1

You could override push on your array...

var movements = [];
movements.push = function(transaction) {
    transaction.date = date();
    return Array.push(transaction);
};

Comments

0

The way you have it currently set up, you would simply replace "date" with the function call to date():

//transactions
var initialBalance = new Transaction(1000,date(),"cash");
var addIn = new Transaction(500,date(),"cash");
var addOut = new Transaction(-300,date(),"card");

But, as others have suggested, there might be better ways to do what you are trying to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.