Day to day counter with Reset button - javascript

I'd like to add a counter to my website which counts in days. However I'd also like to add a button where this can be reset back to 0.
After searching I found the below code, and all is needed now is the button for it. I'm no Javascript expert so any help would be great.
I used this code to create the counter:
<script type="text/javascript">
//Set the two dates
var startdate=new Date(2013, 11, 16) //Month is 0-11 in JavaScript
today=new Date()
//Get 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((today.getTime()-startdate.getTime())/(one_day))+
" days since your last drink!")
</script>
Is there a way I can include a button to reset the start date to the current date (for example if pressed today it would change from 16th of December 2013 to the 19th of December 2013)
Does anyone have any idea how I would do this? I'm fairly new to javascript so just learning the ropes.
Thanks
Gary

#Jonathan has given a good method of achieving this using cookies.This is what most of the sites use to save your preferences.
Another possible way is that you can make use of database to save the startDate for each user and update it accordingly when the reset button is set.The next time you fetch startDate it will be the updated date.You can save it where you are saving his profile information.
If you have small number of users you can also use xml file to store the startDate information and updating it accordingly.
I would go for database or cookies.
Hope it helps

Related

Javascript: Set date, show date +14 days. Update date again after 14 days

I'm trying to write some javascript that tracks an event that occurs every 14 days, so I want to display a NextEvent date and a LastEvent date.
Once the current date == NextEvent date, then that date would become the LastEvent date, and the new NextEvent date would become the current date + 14 days.
I've got this so far, but I don't know how I'd go about updating the dates after 14 days has passed. Only really know HTML, but trying to self-learn more. This has stumped me though.
Any help appreciated!
<script>
var last = new Date();
last.setFullYear(2020, 07, 14);
document.write(""+last);
</script>
<script>
var next = last;
next.setDate(next.getDate() + 14);
document.write(""+next);
</script>
I'm not sure I understand your question correctly. You are searching for a way that updates the date after 14 days? You could use the localStorage and save the date.
Now if you load the site, you would load the date from the localStorage and compare it to the current date to check if 14 days has passed. If it has, just overwrite the value in localStorage to update it. Otherwise is there no value, you would just write the value in the localStorage.
Here is a reference, how to use the localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Calculating date field based on another date field

I need to create a form with 2 date fields.
User will enter first date field (start-date) and I need to calculate 4 weeks from start date in the second date field (one-month-expiry). Better still: is there a way to calculate 1 calendar month instead of weeks?
I've managed to get the second field to populate a date - but it's not correct.
This is JavaScript, which I don't really understand. I've managed to get this far just by googling.
<script type="text/javascript">
document.getElementById('one-month-expiry').value
= (new Date(document.getElementById('start-date').valueAsDate
+ (6.04e+8 * 4)))
.format("dd/MM/yyyy");
</script>
It keeps returning the same date (29/01/1970). So I've obviously managed to stuff something up.
Any ideas how to include the first date field as part of my calculation?
<script type="text/javascript">
let date = new Date(document.getElementById('start-date').valueAsDate);
date.setMonth(date.getMonth() + 1);
document.getElementById('one-month-expiry').value = date.format("dd/MM/yyyy");
</script>
Beware that this might have some issues with edge cases. For example, adding one month to 31st January will give you 31st February, which does not exist, causing the date to roll over to 2nd March instead.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Bootstrap datetime picker picking day before selected

I am using this bootstrap datetime picker. I noticed that when I choose a day and convert the milliseconds using var d1 = new Date(milliseconds); it is converted into the day before my selected day. Is there a particular reason for this?
Example:
I select Tuesday, October 1st:
I log the date object after it is converted:
You must convert it into a Unix timestamp , which is a better way of tracking date/time.
Use new Date('your_date_string').getTime() / 1000 which gives you the timestamp or using PHP (strtotime) .
The date object that is being logged for you is probably coming from your system/browser settings(local).
Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.
While you have the timestamp, cross-check if you are getting the correct time.

Substracting Dates in Javascript return a negative number

I am using the TimeTracker.js from link text to track Page Load times and put them in Google Analytics. Basically what it does is record a start time, and once the page loads it records a end time and then subtracts. These are recored using (new Date()).getTime().
Everything works fine except for instances where the time difference is between 0-100ms. Here I get a massive negative numbers such as -17,183,398,582. Does anyone know what is causing this? Is it got to do with the way Javascript is handling the date substraction or is it something to do with Analytics?
Any help much appreciated. Thanks
Just a guess, but that negative number sounds like it could be linked to Unix epoch time. Example:
var currentTime = new Date().getTime();
currentTime will hold a number such as 1289985468 which represents "GMT: Wed, 17 Nov 2010 09:17:48 GMT".
Perhaps there's a bug in that code you're using.

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources