Page 1 of 1

Javascript question

PostPosted: Wed Jun 15, 2016 9:32 pm
by Laurens
I'm totally struggling with a problem with javascript.

What I am aiming to do is to get today's date in Unix time like this:

var today = new Date();
var date = today.getTime();


Then I want to take that date and run it through a function with 'if, else if' statements. Essentially my aim is to take 'date' and see where in falls in terms of a schedule in which closing times change depending on what week it is. For example:

if (date >1459728000 && date <1460332800){
   return '17.00';
}
else if (date >1460332800 && date <1460937600){
   return '17.15';

(that isn't the whole thing btw)

I cannot for the life of me get this to work. I'm a complete n00b when it comes to javascript, so if you understand what I'm on about, and you can see what I'm doing wrong could you please help me??

My basic aim is to take the date, ask if it is between date x and date y, and if it doesn't to go on to the next line and ask the same (where x and y are different values). It's totally frying my little brain...

Re: Javascript question

PostPosted: Wed Jun 15, 2016 10:01 pm
by Laurens
May have worked out my error, I was working forwards in time, towards the future, whereas if I start 'if' with the furthest date in the future and work backwards, it may work....

Re: Javascript question

PostPosted: Thu Jun 16, 2016 8:43 am
by Laurens
Also realised that the date I was returning was wrong. Now I've divided it by 1000 to get the milliseconds it works fine.

Thanks for reading the most pointless thread ever made.

Sent from my SM-G920F using Tapatalk

Re: Javascript question

PostPosted: Thu Jun 16, 2016 10:26 am
by Prolescum
Nice.

Re: Javascript question

PostPosted: Thu Jun 16, 2016 4:08 pm
by Dragan Glas
Greetings,

One point I noted from your first post, if the date is exactly 1460332800, then the "if-else" clauses will fail.

You need to have either <= in the first line or >= in the second clause.

In other words:

if (date >1459728000 && date <=1460332800){
return '17.00';
}
else if (date >1460332800 && date <1460937600){
return '17.15';

OR

if (date >1459728000 && date <1460332800){
return '17.00';
}
else if (date >=1460332800 && date <1460937600){
return '17.15';

Whichever way you're trying to categorize the date/time.

Kindest regards,

James

Re: Javascript question

PostPosted: Fri Jun 17, 2016 6:30 pm
by WarK


You can compare Date objects directly.

This looks promising: http://momentjs.com/

A short example