How to calculate the number of gaps between two dates in js - javascript

I have two date with time:
YY:MM:DD hh:mm
This is the time period
I need to calculate gap and divide it into 'n' equal parts.
In order to build a graph
Pls Help

Because date is actually saved as an integer and only shown as
YY:MM:DD hh:mm
You can actually just take the two date variables and devide them by the n
gap = (date1 - date2)/n
and then you can get the intervals by just adding the gap multiple times
for(var i = 1; i <= n; i++){
newDate[i] = new Date(date2 + gap*i);
}

something like this?
you can operate directly with dates in javascript
var date1 = new Date(2017, 01, 01, 10, 15, 00);
var date2 = new Date(2016, 12, 01, 10, 14, 45);
var dateDiff = new Date(date1-date2); //this will return timestamp
var years = dateDiff.getFullYear() - 1970; //init date always is 1970
var months = dateDiff.getMonth();
var days = dateDiff.getDate();
var minutes = dateDiff.getMinutes();
var seconds = dateDiff.getSeconds();
alert(years + " years.\r " +
months + " months\r" +
days + " days\r" +
minutes + " minutes\r" +
seconds + " seconds");

I would suggest that you try out the momentjs library. It provides powerful functionalities for you to conveniently work with date objects.
For example, given 2 string dates that are properly formatted, you can get the precise difference between the 2 times easily like so:
let time1 = moment("04/09/2013 15:00:00");
let time2 = moment("04/19/2013 18:20:30");
let diffMilliseconds = time1.diff(time2); // gives the time difference in milliseconds
let diffDays = time1.diff(time2, 'days'); // gives the time difference in days

You can use the date object to convert the given time format to timestamp and then find difference between timestamp.
For example:
var date1 = "2017-03-04 11:22:22"
var date2 = "2017-03-04 13:11:42"
var timestamp1 = Date.parse(date1, "YYYY-MM-DD HH:mm:ss")
var timestamp2 = Date.parse(date2, "YYYY-MM-DD HH:mm:ss")
var difference = timestamp2 - timestamp1;
console.log(difference) //in milliseconds
Now you can divide the difference in to n parts and add to timestamp1 to get following timestamp based on difference/n interval.

Related

Today's date -30 days in JavaScript

I need to get today's date -30 days but in the format of: "2016-06-08"
I have tried setDate(date.getDate() - 30); for -30 days.
I have tried date.toISOString().split('T')[0] for the format.
Both work, but somehow cannot be used together.
setDate() doesn't return a Date object, it returns the number of milliseconds since 1 January 1970 00:00:00 UTC. You need separate calls:
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"
You're saying that those two lines worked for you and your problem is combining them. Here is how you do that:
var date = new Date();
date.setDate(date.getDate() - 30);
document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
<div id="result"></div>
If you really want to subtract exactly 30 days, then this code is fine, but if you want to subtract a month, then obviously this code doesn't work and it's better to use a library like moment.js as other have suggested than trying to implement it by yourself.
Please note that you would be better to use something like moment.js for this rather than reinventing the wheel. However a straight JS solution without libraries is something like:
var date = new Date();
date.setDate(date.getDate() - 30);
sets date to 30 days ago. (JS automatically accounts for leap years and rolling over months less than 30 days, and into the previous year)
now just output it like you want (gives you more control over the output). Note we are prepending a '0' so that numbers less than 10 are 0 prefixed
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2)
// Format date object into a YYYY-MM-DD string
const formatDate = (date) => (date.toISOString().split('T')[0]);
const currentDate = new Date();
// Values in milliseconds
const currentDateInMs = currentDate.valueOf();
const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30;
const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs);
console.log(formatDate(currentDate));
console.log(formatDate(calculatedDate));
Today's date -30 days in this format: "YYYY-MM-DD":
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2021-02-05"
Today's date -30 days but get all days in this format: "YYYY-MM-DD":
var daysDate = [];
for(var i = 1; i<= 30; i++) {
var date = new Date();
date.setDate(date.getDate() - i);
daysDate.push(date.toISOString().split('T')[0]); // ["2021-02-05", "2021-02-04", ...]
}
Simply you can calculate in terms of timestamp
var date = new Date(); // Current date
console.log(date.toDateString())
var pre_date = new Date(date.getTime() - 30*24*60*60*1000);
// You will get the Date object 30 days earlier to current date.
console.log(pre_date.toDateString())
Here 30*24*60*60*1000 refers to time difference in miliseconds.

Javascript/jquery- How to get time closest within an array?

I'm trying to get the closest time in an array or list ect.
I was able to locate this code and have tried to get it to work by making edits but without any luck.
Can use jquery if it makes it easier. below is only javascript though
How can I output the time closest to the time which = thetime
After more research I have found this snippet and think it may be useful for my cause:
var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());
What I'm trying
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) {
minutes = "0" + minutes
}
var thetime = hours + ":" + minutes + " "
var json = [{
"times": {
"times1": "20:01",
"times2": "21:43",
"times3": "22:56",
"times4": "23:21"
}
}]
var times = [];
var jsontimes = json[0].times;
for (var i in jsontimes) {
times.push(new Date(jsontimes[i]))
}
times.sort(function (a, b) {
return Math.abs(thetime - a / new Date()) + Math.abs(thetime - b / new Date())
});
// display code
for (var i = 0; i < jsontimes.length; i++)
document.getElementById("output").innerHTML += dates[i] + "<br>";
You're trying to create Date objects with invalid values (e.g., "20:01"), resulting in invalid dates. According to MDN, you can pass parameters in the following ways when creating a new Date object:
Date(value)
Date(dateString)
Date(year, month, day [, hour, minute, second, millisecond])
where
value is an "integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)." and
dateString is a "string value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 2822 timestamps)."
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
This doesn't really answer your initial question, but it should help you create an array with the values you want.

Get time difference in javascript ISO format

I have a datetime in ISO format i.e.
2012-06-26T01:00:44Z
I want to get the time difference from current time. How can I achieve this using javascript or javascript library Date.js or jquery
This will give you the difference in milliseconds, you can then format it as you want
var diff = new Date("2012-06-26T01:00:44Z") - new Date();
Try this:
var someDate = new Date("2012-06-26T01:00:44Z");
var now = new Date();
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((someDate.getTime()-now .getTime())/(one_day))
alert(diff)
Example fiddle
You can obviously amend the one_day variable to get the difference in the unit you require.
I would suggest converting ISO format to something that works cross browser.
Try this,
var d = "2012-06-26T01:00:44Z";
var someDate = new Date(d.replace(/-/g,'/').replace('T',' ').replace('Z',''));
alert(someDate - new Date());
Edit:
I guess, you need pretty time
Try this awesome code
Edit 2:
You needed reverse, so try this instead
var old_date = new Date();
alert('Old date: ' + old_date.toGMTString())
var new_date = new Date(old_date.setMinutes(old_date.getMinutes() - 5));
alert('Date 5 minutes before: ' + new_date.toGMTString());
If you need timestamp,
alert(new_date.getTime());
in order to format date you can use this function to get the desire format of the date and you can easily change the position of day , month and year.
function convertFormat(inputDate)
var date = new Date(inputDate);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
var fullYear = year + '/' + month + '/' + day
return fullYear;

How to add weeks to date using javascript?

Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.
I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.
My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
document.frmAccept.acceptLicence.value = date1;
}
You can do this :
const numWeeks = 2;
const now = new Date();
now.setDate(now.getDate() + numWeeks * 7);
or as a function
const addWeeksToDate = (dateObj,numberOfWeeks) => {
dateObj.setDate(dateObj.getDate()+ numberOfWeeks * 7);
return dateObj;
}
const numberOfWeeks = 2
console.log(addWeeksToDate(new Date(), 2).toISOString());
You can see the fiddle here.
According to the documentation in MDN
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
This might not answer the question per se, but one can find a solution with these formulas.
6.048e+8 = 1 week in milliseconds
Date.now() = Now in milliseconds
Date.now() + 6.048e+8 = 1 week from today
Date.now() + (6.048e+8 * 2) = 2 weeks from today
new Date( Date.now() + (6.048e+8 * 2) ) = Date Object for 2 weeks from today
You're assigning date1 to be a Date object which represents the string you pass it. What you're seeing in the acceptLicense value is the toString() representation of the date object (try alert(date1.toString()) to see this).
To output as you want, you'll have to use string concatenation and the various Date methods.
var formattedDate = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
In terms of adding 2 weeks, you should add 14 days to the current date;
date1.setDate(date.getDate() + 14);
... this will automatically handle the month increase etc.
In the end, you'll end up with;
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
N.B Months in JavaScript are 0-indexed (Jan = 0, Dec = 11), hence the +1 on the month.
Edit: To address your comment, you should construct date as follows instead, as the Date argument is supposed to be "A string representing an RFC2822 or ISO 8601 date." (see here).
var segments = acceptCompletionDate.split("/");
var date1 = new Date(segments[2], segments[1], segments[0]);
This should do what you're looking for.
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
}
To parse the specific dd/mm/yyyy format and increment days with 14 , you can do something like split the parts, and create the date object with y/m/d given specfically. (incrementing the days right away) Providing the separator is always -, the following should work:
function LicenceToOccupy(acceptCompletionDate)
{
var parts = acceptCompletionDate.split("/");
var date1 = new Date(parts[2], (parts[1] - 1), parseInt(parts[0]) + 14); //month 0 based, day: parse to int and increment 14 (2 weeks)
document.frmAccept.acceptLicence.value = date1.toLocaleDateString(); //if the d/m/y format is the local string, otherwise some cusom formatting needs to be done
}
date1.toLocaleDateString()
Thiswill return you date1 as a String in the client convention
To create a new date date2 with 2 weeks more (2weeks = 27246060 seconds):
var date2 = new Date(date1 + 60*60*24*7*2);

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources