0

I want display my var value extacly below another var, here my example.

var d = new Date();
var alldifftime = (d.getFullYear()+','+  d.getMonth()+','+  d.getDate()+','+  (d.getHours()-7)+','+  d.getMinutes()+','+  d.getSeconds());

var difftime = new Date() - new Date(Date.parse(new Date(alldifftime)));

how to become

var difftime = new Date() - new Date(2016,11,26,19,41,48);

2016,11,26,19,41,48 is the present time.

Thanks.

3 Answers 3

2

The reason the code you shared does not work as intended is that the concatenation operator transforms number values into strings. Try the following:

var d = new Date(),
    dYear = d.getFullYear(),
    dMonth = d.getMonth(),
    dDate = d.getDate(),
    dHours = d.getHours() - 7,
    dMinutes = d.getMinutes(),
    dSeconds = d.getSeconds();

// difftime will contain the time difference between the two dates in milliseconds
var difftime = new Date() - new Date(dYear, dMonth, dDate, dHours, dMinutes, dSeconds);
Sign up to request clarification or add additional context in comments.

2 Comments

really quick response, I am newbie here, sorry for my stupid question, but I appreciate it, thanks, it's work.
@StanleyAngelino please do upvote our answers and/or mark one as correct if they helped you. thanks!
0

If you want get the difference between two dates, it is more simplify with momentjs: http://momentjs.com/docs/#/displaying/difference/

var dateNow = moment();
var dateBefore = moment().subtract(7, 'hours');
var dateDiff = dateNow.diff(dateBefore, "hours");

1 Comment

awesome. solve my problem, I never use moment.js before.
0

To get a Date that is 7 hours prior to a first date, copy the date and set the hours to 7 hours ago. To get the difference between two dates, just subtract one from the other to get the difference in milliseconds and convert to whatever time unit(s) you want (say hours):

// Now
var d0 = new Date();
// Copy for then
var d1 = new Date(d0);
d1.setHours(d1.getHours() - 7);
console.log('The time now: ' + d0.toString() + 
            '\n7 hours ago : ' + d1.toString());

console.log('Diff time: ' + ((d0 - d1)/3.6e6) + ' hours'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.