0

PHP Works like this

<?php
$x = "";
$now = gmdate('H:i');
$one = "22:30";

$timenow = strtotime($now);
$timeone = strtotime($one);

if ($timenow > $timeone) 
{
 $x = "time now is more than time one";
}
elseif ($timenow < $timeone)
{
 $x = "time now is less than time one";
}
?>

Now for the Javascript

var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var now = hour + ":" + minute;
var one = "22:30";
var x = "";

if (now > one)
{
 x = "time now is more than time one";
}
if (now < one)
{
 x = "time now is less than time one";
}

I want to store times in an array just as something like "22:00".

Then change the string into a time variable but only holding the Hour and Minute,

Then feed that into a for loop and a if statement to see which is larger

The php code works but I want to learn to do the same thing using Javascript

Any assistance appreciated.

Sanctus
  • 69
  • 2
  • 8
  • why downvote? cant figure out how to do the php equivalent in javascript :/ – Sanctus Dec 14 '13 at 09:19
  • 2
    I did not down vote, but probably because a short search for js time comparison will e.g. give this question on SO [How can I compare two time strings in the format HHMMSS](http://stackoverflow.com/questions/6212305/how-can-i-compare-two-time-strings-in-the-format-hhmmss). You should show that you did at least some research by showing similar questions and tell why the answers of these wont work for you. – t.niese Dec 14 '13 at 09:40
  • thx for the link I've been trying to do just that yet I get a wrong result when I run my code http://jsfiddle.net/NGZWb/ – Sanctus Dec 14 '13 at 09:48

2 Answers2

1

PHP works with comparing strings very similar to JS... actually in your case of comparing time is exactly the same:

<?php
$x = "";
$now = gmdate('H:i');
$one = "22:30";

if ($now > $one) 
{
    $x = "time now is more than time one";
}
elseif ($now < $one)
{
    $x = "time now is less than time one";
}

The only thing you need to worry in JS is case of hour < 10 or minute < 10 then you need to prepend leading zero to have same string HH:mm like php date format "H:i" would provide:

function leadZero(num) {
    return num < 10? '0' + num.toString() : num;
}
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var now = leadZero(hour) + ":" + leadZero(minute);
var one = "22:30";
var x = "";

if (now > one)
{
    x = "time now is more than time one";
}
else if (now < one)
{
    x = "time now is less than time one";
}
Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30
0
var dateString = "date is: ";
var newDate = new Date();

// Get the month, day, and year.
dateString += (newDate.getMonth() + 1) + "/";
dateString += newDate.getDate() + "/";
dateString += newDate.getFullYear();

document.write(dateString);
saloni
  • 121
  • 4