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

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.

Related

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

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.

TypeError: *.getMonth is not a function

I'm trying to build a javascript function that will auto-fill 14 days of a calendar with dates leading up to the last date, which is picked by a datepicker. So far my code is:
function filldates() {
datepicked = document.getElementById("period-ending").value;
s = datepicked.split('/');
enddate = new Date(s[2], s[0], s[1]);
date1 = enddate.setDate(enddate.getDate()-14);
day1 = date1.getMonth() + 1;
month1 = date1.getDate();
var firstday = day1 + '/' + month1;
document.getElementById("date-1").value = firstday;
}
However the developer's console keeps telling me that date1.getMonth is not a function. I'm confused because all of the tutorials and examples I've been looking at are based around something like: "var today = new Date(); var month = today.getMonth() + 1;"
Is this an implementation problem?
The setDate() function mutates its context date. It does not return a new Date instance.
If you want to create a new date instance that's some number of days ahead of another one:
function daysAfter(d, days) {
var nd = new Date(d.getTime());
nd.setDate(d.getDate() + days);
return nd;
}
Then if you've got a date, you can create a date 14 days after it like this:
var someDate = ... whatever ... ;
var fourteenDaysAfter = daysAfter(someDate, 14);
You can then use the .getMonth() and .getDate() accessors to do whatever formatting you want. Keep in mind that months are numbered from zero in JavaScript.
edit for dates before a date just pass a negative number.

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

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);

jQuery Format Time

I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM or 10.00 PM.
Is there a jQuery function that is able to do this?
Please help.
Thanks
There is Date object in pure javascript, no jQuery needed.
http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
JavaScript's own Date object, using the getHours() and getMinutes() functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").
DateJS, an add-on library that does a huge amount of date stuff (although sadly it's not actively maintained)
PrettyDate from John Resig (the creator of jQuery)
To use just about any of those, first you have to turn that "milliseconds" value into a Date object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10) and then use new Date(num) to create the Date object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10)) gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000) gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date() to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
Using T.J.'s solution this is what I ended up with.
var date = new Date(parseInt("77771564221", 10));
var result = new Array();
result[0] = $.datepicker.formatDate('DD, M, d, yy', date);
result[1] = ' ';
if (date.getHours() > 12) {
result[2] = date.getHours() - 12;
} else if (date.getHours() == 0 ) {
result[2] = "12";
} else {
result[2] = date.getHours();
}
result[3] = ":"
result[4] = date.getMinutes();
if (date.getHours() > 12) {
result[5] = " pm";
} else {
result[5] = " am";
}
console.log(result.join(''));

Categories

Resources