0

I'm not that good at javascript (yet), so I need some help, with an alternative version of this php script (In javascript)

function until($format = ""){
    $now = strtotime("now");
    $nextTuesday = strtotime("-1 hour next tuesday");
    $until = $nextTuesday - $now;
    if(empty($format)){
        return $until;
    }else{
        return date("$format",$until);
    }
}

Just need it to count down, until next tuesday, in a really short way (Not in 20+ lines, like all the other script I've seen) It should still return a timestamp, if it's possible (Need it for an offline app)

So if anyone could help me, I would be really happy (Not that I'm not happy right now, but I would be even happier) :D

3
  • Javascript has some similar date functions, however, the "-1 hour next tuesday" might not be possible to achieve. Source: w3schools.com/jsref/jsref_obj_date.asp Commented Aug 9, 2011 at 18:33
  • 1
    Check out datejs Commented Aug 9, 2011 at 18:35
  • 2
    Getting the difference between today and next tuesday in JavaScript is trivial. But you are also asking for a date format parsing engine in less than 20 lines of code. Date formatting is not built in to JavaScript. You can manually format a date in 1 line of code, but you can't reasonably parse a format string and return a formatted date string in under 20 lines of code. Use an existing library or write your own Date formatting engine. Commented Aug 9, 2011 at 20:10

3 Answers 3

2

You may want to take a look at the phpjs site. They have code showing how a substantial number of PHP functions can be done in JS.

Specifically: strtotime and date

0
0

JS doesn't have anything remotely close to strtotime. You'd have to determine "next tuesday" yourself. Once you've got that, you can extract a timestamp value using .getTime(), which will be the number of milliseconds since Jan 1/1970. This value can also be fed back into a new date object as a parameter, so you can do date math using simple numbers externally, then create a new date object again using the result.

e.g.

var now = new Date();
var ts = now.getTime();
var next_week = ts + (86400 * 7 * 1000);
next_week_object = new Date(next_week);

Once you've got the "next tuesday" code figured out, the rest is trivial

0

To get milliseconds till the next tuesday (nearest in the future):

function f_until(){
  var now = new Date(Date.now());
  var nextT = new Date(Date.now());
  var cD = nextT.getDay();
  if(cD < 2)nextT.setDate(nextT.getDate() + (2-cD));
  else nextT.setDate(nextT.getDate() + (9-cD));
  nextT.setHours(nextT.getHours() - 1);
  //alert('next tuesday: '+nextT.toString()); 
  return nextT.getTime() - now.getTime();
}

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.