-1

I really need help calculating the difference between two dates and it has to be the number of days in a whole number. Here is my HTML and jQuery..

This is not working at all... The site should say the date today. Then the user would picka date and click the button "Check our safety record" and at the bottom of the page it says how many days it has been. The jQuery:

$(document).ready(function() {
    $('#safetyRecord').hide();

var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

var newDate = new Date();
newDate.setDate(newDate.getDate());    
$('#today').html(dayNames[newDate.getDay()] + "," +' ' + monthNames[newDate.getMonth()]      + ' ' + newDate.getDate() + ","+ ' ' + newDate.getFullYear());

/*
$(':button').click(function(){
var start = $('#dateOfLastAccident').val();
var end = $('#today');

var startDate = new Date(start);
var endDate = new Date(end);

var diff = endDate - StartDate;

var numDays = Math.floor( diff / 1000 /60 /60 /24 );
$('#daysSinceLastAccident'+ numDays)();
*/
});

The HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>generic safety</title>

    <link rel="stylesheet" href="L3hw.css">

    <!-- jQuery library hosted by Google Content Distribution Network -->
    <script   src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="L3hw.js"></script>

</head>
<body>
    <header>
        <img src="images/genericBanner.png" alt="Generic, Inc.">
        <p>
            The New Ventures Mission is to scout profitable growth   opportunities in
            relationships, both internally and externally, in emerging, mission-inclusive
            markets, and explore new paradigms and then filter and communicate and
            evangelize the findings.
        </p>
    </header>

    <section id="main">
        <h1>Safety at generic company</h1>
        <h2>Today is <span id="today">TBD</span>.<br>
            Our last lost-work accident was on
            <input type="date" id="dateOfLastAccident">
            <button type="button" id="checkRecord">Check our safety  record</button>
        </h2>
        <h2 id="safetyRecord">
            It has been <span id="daysSinceLastAccident">TBD</span> days  since our last lost-work accident.
        </h2>
    </section> <!-- end main -->

    <footer>
        <p id="message">
            <!-- (an appropriate safety message will appear here) -->
        </p>
        <p><img src="images/genericBullet.png" alt="*"> Generic Company - we  do stuff</p>
    </footer>
</body>
</html>
Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
  • 2
    ALL CAPS IS LIKE SHOUTING... PLEASE DON'T SHOUT!!! – tjons Oct 08 '13 at 01:34
  • 2
    This might give you some insight `:)` http://stackoverflow.com/questions/10931288/how-to-add-subtract-dates-with-javascript/10931362#10931362 – Tats_innit Oct 08 '13 at 01:34
  • sorry i have never used this website so, i was trying to separate it from the code. And i am not using a datepicker i'm just using an input type=date in the html – user2856563 Oct 08 '13 at 01:39
  • You should use a datepicker. – tjons Oct 08 '13 at 01:39
  • Also, please see the FAQ in the help center. – tjons Oct 08 '13 at 01:40
  • Yeah it would make life easier.. but this is for a programming class and that is not required. – user2856563 Oct 08 '13 at 01:40
  • Why do you want to program? To get by? Add a datepicker. Your professor and classmates will be impressed. – tjons Oct 08 '13 at 01:41
  • Are you required to use jQuery? – tjons Oct 08 '13 at 01:44
  • This isn't supposed to be difficult...I am doing a web development program because I want to learn web design.. and they make you take some programming classes – user2856563 Oct 08 '13 at 01:47
  • yes i have to use query – user2856563 Oct 08 '13 at 01:48
  • When the user clicks the button with id "checkRecord": Read the user-entered date from the input element with id "dateOfLastAccident". – user2856563 Oct 08 '13 at 01:50
  • Calculate the whole number of days since that date, storing the number in a variable. You may need to use Math.floor() or equivalent to change the result to a whole number. Replace the content of the element with id "daysSinceLastAccident" with the number of days accident-free. Thats the instructions I have been stuck on this all day because everyone say use datepicker but I can't. – user2856563 Oct 08 '13 at 01:51

5 Answers5

3

Although jQuery makes up for many of Javascript's lackings, and although Date support is one of Javascript's lackings, jQuery does not help you with dates. So, you have chosen the wrong tool for the job, as many others here have noted.

The jQueryUI DatePicker will do much of this for you if you use it as it was intended (to show a datepicker), and do a poor job of doing parts of this for you, like just calculating days between dates, because it decomposes rather poorly.

I join others in questioning why you aren't using that - it may be you just didn't know it exists, or that you noticed it's a bit of a monster and not wonderfully written. These are valid accusations, but I warn you that dates and calendars are one of many famous Pits of Despair developers fall into. The deadly region where humans think of something as simple, and computers and reality lash back long after you've coded your way into the details, when it's much, much too late to cut your losses and feel good about it.

If the mess you're in isn't enough to convince you that things are bad when you get into dates and date formatting and will only get worse, here's part of an old Quora answer of mine:

For example, if you tell me all quotes in a system expire in 10 days, I might say fine, that's simple, and estimate that expiration task as an hour. If I estimated a week for this, you'd call me crazy.

Then I attempt to code it. When do they expire, at midnight, or the time they were provided? How do I expire them - do I write a job that continuously wakes up and expires old quotes? Do I wait for users to check for them and expire old quotes there while I make the user wait?

Then I find out it's actually 10 business days. What's a business day? How do I advance the date properly so I skip weekends? What's the holiday schedule? What about leap years? When IS a leap year? (hint: It's not every 4 years. It's not every 4 years except every 100, either.)

OK, we'll build an interface for you to maintain the holiday schedule, since it's subject to change.

Then I find out you want the user to receive a warning email the day before a quote expires. Not a day, a business day. In their timezone. Make sure it only goes out during business hours where they are.

HOW did an hour turn into 2 weeks?

So cut your losses. Use jQueryUI Datepicker.

Community
  • 1
  • 1
Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
1

Firstly you need to work out what "difference in days" means, e.g.

2013-10-11T00:00:01 - 2013-10-10T23:59:59 => 1 day or 2 seconds?

A difference in days is fairly simple using UTC values if you can ignore the time component:

// Expects ISO8601 format yyyy-mm-dd
function toUTCDate(s) {
  s = s.split(/\D/g);
  // Re-order arguments for other formats
  return new Date(Date.UTC(s[0], --s[1], s[2]));
}

function daysDiff(dateString) {
  var msInDay = 8.64e7
  var now = new Date();
  var nowUTC = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()); 
  return (nowUTC - toUTCDate(dateString)) / msInDay;
}

console.log(daysDiff('2013-09-30'));  // 8 for 8 October 2013

If you have two string dates, the daysDiff function can be as simple as:

function daysDiff(d0, d1) {
  return (toDate(d1) - toDate(d0)) / 8.64e7;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
0

I would suggest that you use a datepicker, and that you rethink why you are programming. If you are not using the correct tool because it is not required, you should not be doing programming.

I feel like I shouldn't be doing your homework, but... here is a rough idea (in Normal JS, not jQuery):

function funC(){
//here is the date today...
var d=new Date();
var i = getElementById("today")'
i.InnerHTML= d;
//here is a function for the days since the date
var e = getElementById("dateOfLastAccident");
var x = d-e;
var y = //insert your own algo to format dates
var a = getElementById("daysSinceLastAccident");
a.InnerHTML = y; 
}

PLEASE NOTE THAT THIS WILL NOT WORK BY ITSELF. YOU STILL HAVE WORK TO DO. AND YES, I AM SHOUTING!!!

tjons
  • 4,749
  • 5
  • 28
  • 36
0

Ya, why don't you use datepicker? I don't know how to calculate date formatted string in javascript, but i know that we can calculate the date formatted string in PHP. So, if you want to use jquery you should use ajax too. (I don't use datepicker, so insert the date manually) It's the PHP:

<?php 
$datefr = strtotime($_REQUEST['datefr']);
$dateto = strtotime($_REQUEST['dateto']);

$result = ($dateto-$datefr)/(3600*24); //convert 'secon' to 'day'

echo $result;
?>

It's the HTML :

<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script>
function calculate(){
var datefr = $("#datefr").val();
var dateto = $("#dateto").val();

$.ajax({
url : "caculate.php",
type: "POST",
data : "datefr="+datefr+"&dateto="+dateto,
success : 
function (data){
$("#result").val(data);
}
});

}
</script>
<input type="text" id="datefr"><input type="text" id="dateto">
<input type="button" onclick="calculate()" value="Calculate">
<br>
<input type="text" readonly id="result">day(s)

Try this, you will see the result!
(both of the date that will be inserted must be in 'yyyy-mm-dd' or 'dd-mm-yyyy' format)

Oki Erie Rinaldi
  • 1,835
  • 1
  • 22
  • 31
0

Should you use a date picker, yes. Do you need to, no. With Google Chrome and the HTML you provide (input type='date') you get one for free. The commented out code you supplied is very close to doing what you need. I'm not going to give you the answer but give you pointers, seeing this is homework and all.

$(':button').click(function(){
var start = $('#dateOfLastAccident').val();
var end = $('#today'); //Perhaps use what you used to popluate #today,this code won't get text or value, just an object

var startDate = new Date(start);
var endDate = new Date(end);

var diff = endDate - StartDate; //javasctipt is case sensative

var numDays = Math.floor( diff / 1000 /60 /60 /24 );
$('#daysSinceLastAccident'+ numDays)(); //not how jQuery sets text: http://api.jquery.com/text/
//dont forget to show what is hidden: http://api.jquery.com/show/

This is the bare bones, but should get you where you need to go.

Also learn about javascript debugging, using alerts for debugging, or better still logging to the console for debugging, where the javascript console is (hint in chrome f12 is your friend).

Jon P
  • 19,442
  • 8
  • 49
  • 72