show remaining time left after user input - javascript

I am trying to show the remaining time left after the user inputs their answer.
so it's suppose to be like this.
When does that course start? 2022-09-05 (user input)
Today it is 32 days left until the course starts
I dont think its suppose to be that complicated but I cant make it work, I keep getting NaN or that it just isnt working.
I have checked MDN but I just dont get it.
The code looks like this.
function start(timePassedIn) {
return `Today it is ${timePassedIn} days left until the
course starts`;
}
const course = prompt("When does that course start? ");
const starting = start(course);
console.log(starting);
I removed all my attempts at the date so that you can give me fresh input.
Appreciate all the help I can get.

Can you try this.
function start(timePassedIn) {
return `Today it is ${timePassedIn} days left until the
course starts`;
}
function getDateDifference(inputDate) {
const date1 = new Date(inputDate);
const date2 = new Date();
const diffTime = Math.abs(date1 - date2);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
}
const course = prompt("When does that course start? ");
const starting = start(getDateDifference(course));

dates can be stored in two ways in a program:
as a String, for example "October 10th" or "2022-08-01" or "09/11"
as Date Objects. You already found the documentation for Date in MDN.
we use Strings for input and output, and Date Objects for computation like the difference between two dates.
If I understand you correclty, your program should
ask the user when the course starts
compute how many days are left until the course starts
output the number of days
When you try to program this step 2 is the complicated one:
1. ask the user when the course starts:
`const course = prompt("When does that course start? ");`
course will contain a string with the date. maybe you would be
better off to ask for day and month seperatly?
const month = prompt("When does that course start? Please enter the month as a number");
const day = prompt("When does that course start? Please enter the day as a number");
2. compute how many days are left until the course starts
a) convert the input into a Date object.
b) get a date object of the current date
c) compute the difference and convert to days

Related

Finding number of days between two dates in javascript/redux

let oneDay = 24*60*60*1000;
let firstDate = new Date();
let secondDate = this.props.eventData.date
let finalSecDate = new Date(secondDate)
var timeDiff = Math.abs(firstDate.getTime() - finalSecDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
I am trying to calculate the number of days between two dates using javascript in a redux project. (My second date variable above is based on the date that a user enters and then I am changing it into a new Date format.) The above code works but when the event has passed the the number of days until the event is still coming up as positive number of days. Can someone please help me distinguish whether or not the date has passed so I can get the negative number of days.
I appreciate any help you can give, thank you !
I would recommend using Moment.js, since they have a number of date functions that will become useful as you play around with dates more.
Here's what it would look like if you wanted to find the difference between two dates:
var present = moment();
var end = this.props.eventData.date;
present.diff(end, 'days') // 5
The diff function finds the difference between the two dates. It also solves your problem of returning a negative value if the date already passed.
var present = moment();
var past = moment('2014-02-03 12:53:12');
past.diff(present, 'days') // -1379

How do I get difference between two dates of unknown format in javascript?

I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);

Difference between two time object

Am trying to get number of hours between two time objects. Am using 24h time format. If the difference in hours is higler than 24 hours, I want to increase price for some cars.
User can select start time and end time from input typte=time: 10:25 / 23:45
Which is the best approach to do this. I google but that examples i dont understand clearly...
Just subtract them if they are date objects, if they are not make them.
You can get the amount of hours between two dates with:
var date1 = new Date('2016,03,10');
var date2 = new Date();
var hoursBetween = ((date1-date2)/1000)/3600;

Why is this PDF javascript Date being incorrectly calculated only once a year?

I have an interesting result from the javascript in an Acrobat PDF Form
I have a series of date form fields. The first field is for user entry and the remaining fields are calculated by javascript, each field incremented by one day.
The code is:
var strStart = this.getField("userField").value;
if(strStart.length > 0) {
var dateStart = util.scand("dd/mm/yy",strStart);
var dateStartMilli = dateStart.getTime();
var oneDay = 24 * 60 * 60 * 1000 * 1; // number of milliseconds in one day
var dateMilli = dateStartMilli + oneDay;
var date = new Date(dateMilli);
event.value = util.printd("dd/mm/yy",date);
} else { event.value = "" }
The issue is if I input 05/04/15 in to the user field the result is 05/04/15 (same, wrong) while any other date of the year correctly increments by one day (ie 25/10/15 gives 26/10/15, 14/2/15 gives 15/2/15 etc)
The same error occurs on the 3rd of April 2016, 2nd of April 2017, etc (ie each year)
I have a fortnight (14) of these incrementing fields, each incrementing the date from the previous calculated field with the same javascript as above ("userField" is changed to date2, date3, date4 etc). What is very strange is that the next field that increments off the second of the two 05/04/15 correctly returns 06/04/15 and there isn't an issue after that.
Does anyone know why this might be?!
That doesn't happen on my browser's JavaScript engine and/or in my locale, so it must be an Acrobat thing or that date may be special in your locale (e.g., DST).
In any case, that's not the correct way to add one day to a JavaScript date, not least because some days have more than that many milliseconds and some have less (transitioning to and from DST).
The correct way is to use getDate and setDate:
var strStart = this.getField("userField").value;
if(strStart.length > 0) {
var dateStart = util.scand("dd/mm/yy",strStart);
dateStart.setDate(dateStart.getDate() + 1); // Add one day
event.value = util.printd("dd/mm/yy",dateStart);
} else { event.value = "" }
setDate is smart enough to handle it if you go past the end of the month (per specification).
If it's DST-related, the above will fix it. If it's some weird Acrobat thing, perhaps it will work around it. Either way, it's how this should be done.
Let me guess, that's the day daylight savings starts in your locale? 24 hours after midnight is not always the next day, because some days have 25 hours.
Approaches that come to my head:
manipulate the day. (This is easy if Acrobat allows dates like the 32nd of January, because oyu can just increment the day. Otherwise, maybe don't bother because leap years aren't much better than DST.)
don't start from midnight. If you never use the hour and minute within the day, don't pin your day at the strike of midnight, but at, say, 3am. After a change in DST status, later days in your fortnight might register as 2am or 4am, but as long as you're only using the day…

Number change every 24 hours

I would like to provide a list of about 40 positive numbers and then have my home page display the first number. Then at midnight, the number will change to the next number in the list. When at the end of the list, the rotation starts over. So for instance, a user goes to my page several times today and sees the first number in the list. Then say 1:00am, they go back to the page and see the next number on the list and will do so until midnight tomorrow night...etc etc etc Is this possible?
I've tried several different javascripts that does change the number according to my list BUT when a user goes to the page, it starts the list over again.
I am so new to this, I don't know which part of my code you might need since what I have been trying does what its supposed to do...just not how I want it to do.
Do I make sense?
Unfortunately, I won't be able to use php for this webpage.
You can use new Date().getTime() to get the current time in milliseconds. If you convert that to days, and round down, you can find the number of days since the epoch. Take the modulo of that and use it to obtain the index of your array of numbers. Since you're always using the current time (according to the user), you don't need to store any cookies or server-side counter.
var nums = [1,1,2,3,5,8,13]; // and so on
d = new Date(), // today
days = d.getTime() / (1000*60*60*24),
idx = Math.floor(days) % nums.length;
alert(nums[idx]); // should change once a day
Define a start date (preferably in the past), calculate today's date, subtract the two, and then use modulo to squeeze it into the range of numbers you want to show:
var minDate = 15681, // days since 1-1-1970
nowDate = Math.ceil(new Date().getTime() / 1000 / 86400),
numbers = [1, 5, 1234, 6543, 1236456];
// get the number for today
console.log(numbers[(nowDate - minDate) % numbers.length]);
If the start date doesn't matter, you can simplify the expression to:
numbers[Math.ceil(new Date().getTime() / 86400000) % numbers.length];
Btw, this won't change at midnight for everyone btw, because .getTime() gives GMT time.

Categories