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
Related
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
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);
I am trying to calculate how many minutes a worker works from the input starting and ending time(e.g. 10:30 am to 3:30pm). Could u guys help how to calculate them? Could u check my code and correct them? I am very new in Javascript.
function myFunction(){
var sTime=document.getElementById("startTime").value;
var eTime=document.getElementById("endTime").value;
var diff = sTime-eTime;
var result= diff.getMinutes();
document.getElementById("demo").innerHTML=result`;
https://jsbin.com/bolapox/edit?html,output
You will need to turn the users input into a usable format with Date().parse(input). This returns the number of milliseconds since 1 January, 1970, 00:00:00, local time.
You can then take the difference in milliseconds and convert them into minutes.
var sTime=Date().parse(document.getElementById("startTime").value);
var eTime=Date().parse(document.getElementById("endTime").value);
var diff = eTime - sTime;
var result = diff / 60000;
You should consider Moment.js, here yiou can find some examples:
http://momentjs.com/docs/#/durations/
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;
I have a web application where I wish to send information to a database.
I have a datepicker, which lets the user select a date and formats the date as "YYYY-MM-DD". In addition to this, the users must also select a time using a timepicker which formats the time as "HH:MM". This gets concatenated into a DateTime string as "YYYY-MM-DD HH:MM".
I need to convert this into milliseconds for the datetime to be accepted as the correct format on the database (locale format of YYYY-MM-DD HH:MM:SS.mmm).
I have a tried a host of solutions found here and elsewhere to try and convert into milliseconds. Whenever I try to concat then convert I usually get a NaN error or "invalid Date" and I cannot simply add the converted milliseconds.
Is there any way of doing this in jQuery or JavaScript?
>> var datetime = new Date();
undefined
>> datetime.getTime();
1332613433314
Date.getTime() returns the number of milliseconds since 1970/01/01:
This should be handled server-side, though.
I managed to figure this one out myself. Thanks to those who answered. Its not an ideal solution, but it works.
var d = $("#date").val();
var dateParts = new Date((Number(d.split("-")[0])), (Number(d.split("-")[1]) - 1), (Number(d.split("-")[2])));
var dateis = dateParts.getTime();
var timeEnd = $("#endtime").val();
var time1 = ((Number(timeEnd.split(':')[0]) * 60 + Number(timeEnd.split(':')[1]) * 60) * 60) * 1000;
var timeStart = $("#starttime").val();
var time2 = ((Number(timeStart.split(':')[0]) * 60 + Number(timeStart.split(':')[1]) * 60) * 60) * 1000;
var dateTimeEnd = dateis + time1;
var dateTimeStart = dateis + time2;
What this basically does, is take a date from a datepicker, and a start and an endtime from a timepicker. The ajax accepts 2 datetimes, one for start, one for end. The above solution basically gets all the values from the input values, and converts it to milliseconds. It's not the best way of doing things but it is a quick fix.
I don't realise your actual question, but I've made a code that set the datepicker to a minimum selected day as today the code is as follows :
$("#datefield").datepicker({
dateFormat:"yy-mm-dd",
minDate:new Date(new Date().getTime())
});
The return value of the new Date().getTime() is the milliseconds from 1970/01/01 05:30 am (as my system)
Can you use the JavaScript Date object?
You could use it like so:
var d = new Date(yyyy, MM, dd, hh, mm, 0, 0).getTime();
You initialize the Date object and then use the getTime function to return the number of milliseconds since Jan. 1, 1970.
$("#datefield").datepicker("getDate").getTime(); will do the trick
I would do this on the server side and use the strtotime function to convert to a timestamp which will give you a number of seconds which if you really need milliseconds for some kind of script : 1 second = 1000 milliseconds.
If anything you could use jquery to validate that you'll be sending a valid date-time to the server side script before you do so.