Setting a date without Setting TIme Javascript - javascript

I m trying to do the following :
Storing Current day +1 (Tomorrow's date) ( CurrentDay is the StartDay,wrong naming alias,my bad)
calculating 7 days from date from 1st Step
Everyday checking presentDay, and if is equal to 7th day, run my logic.
Problem I m facing is :
The DateObject I store is in a numerical format and it also saves the time. I want only the date for comparison.
Is it possible to directly compare dates? I do not really wish to use 3rd party library.
Any help will be appreciated.
Code :
var d = new Date();
var stdate = d.setDate(d.getDate() + 1); //output something like 1526407850028 ( last few digits changes every second)
var weeklyDate = new Date();
var wkdate = weeklyDate.setDate(weeklyDate.getDate() + 7); //output Ex : 1526926307437
var presentDay = new Date();
var pdate = presentDay.setDate(presentDay.getDate());
if (pdate == wkdate) { // I want only date comparison
// my logic
}

Try keeping your steps more separate. For instance, why not just compare the date values by calling Date.prototype.getDay()? Then you're not working with all of that other stuff. You can also reduce the number of calls to new Date(), so the whole thing would be:
//calculate target date
let d = new Date(); // returns an integer between 0-6
var stDay = (d.getDay()+1)%7; //tomorrow's day of week kept between 0-6 by modulus
//daily check runs in separate function
let today = new Date();
if( today.getDay() === stDay){
//logic
}
developer.mozilla.org - Date.prototype.getDay()

Related

Checking if date is greater than today

Trying out a Jquery to confirm if date selected is equal to today or greater than.
If i select today, it return it as the day selected is less than today. Selecting previous day works well but selecting today returns less than. Any tip.
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.getTime()) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
Don't forget that new Date() will include the current time as well. You'll need to remove that time component with today.setHours(0,0,0,0) for the comparison to be correct.
Also, setHours() returns the underlying value like getTime() so you can do
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.setHours(0,0,0,0)) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
In response to the comment about adding 20 days:
This is a little more detailed but is fairly easy.
var today = new Date();
var plus20Days = new Date(today.setDate(today.getDate() + 20));
again you can then use setHours() to reset the time component.
new Date() considers time too, not only the date. I think the easiest way to achieve this is to compare years, months and days by using respectively getFullYear() , getMonth() , getDate().
Check all the methods that manipulate js Date here
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Date

get an array of dates from today for datepicker with Javascript

I am trying to write a function that returns an array of dates from today till the maximum date, so that I can restrict the date picker selection. At the moment I have the following:-
datesAfterToday: function (date) {
var dates = []
var currentDate = new Date()
var endDate = new Date(8640000000000000).getFullYear()
var addDays = function (days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() + days)
return date
}
while (currentDate <= endDate) {
dates.push(currentDate)
currentDate = addDays.call(currentDate, 1)
}
return dates
}
and then I am using Vue.js to mount it as follows :-
mounted () {
this.allowedDates = this.datesAfterToday
},
however I am only getting an array of objects instead of the proper array.
How can I get the proper array of dates so that I can bind it to the allowdates property.
Thanks for your help and time!
For starters new Date(8640000000000000).getFullYear() will set endDate to the year of that date, which is 275760. currentDate will be today's date (in milliseconds), which at the time of me writing is 1511272934156. As you can see currentDate is always greater than endDate, so your while loop never goes to the statements inside.
Another issue is that the date you picked is really far in the future and you're populating an array one day at a time. Your loop will most likely make the page freeze or crash completely. Try picking a date that's more manageable.
For instance, in the snippet below I set endDate by first initializing it to today, then setting the year to exactly one year from now. This gives me an array with roughly 365 values.
You can imagine how big this array would be if I used a year that was 273,748 years in the future.
var dates = []
var currentDate = new Date()
var endDate = new Date()
endDate.setFullYear(endDate.getFullYear()+1)
var addDays = function (days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() + days)
return date
}
while (currentDate <= endDate) {
dates.push(currentDate)
currentDate = addDays.call(currentDate, 1)
}
console.log(dates)
With all that being said, it looks like you're actually allowed to pass an object specifying the minimum and maximum values rather than an array.
https://vuetifyjs.com/components/pickers#example-6
let d = new Date() // today
let d2 = new Date()
d2.setFullYear(date.getFullYear()+1) // Next year
this.allowedDays = {
min : d.toISOString().substr(0, 10), // e.g. 2017-11-21
max : d2.toISOString().substr(0, 10)
}
Another option would be to use vuejs-datepicker For example:
<script>
var state = {
disabled: {
to: new Date(), // Disable all dates up to specific date
from: new Date(8640000000000000) // Disable all dates after specific date
}
}
</script>
<datepicker :disabled="state.disabled"></datepicker>
See Disabled Dates in the documentation.

parse.com - how i can create query equal createdAt by date only with javascript

I want to find data by "createdAt" field but i need to search with date only (without time).
var d = new Date();
var query = new Parse.Query("TableName");
query.equalTo("createdAt", d);
What you basically have to do to generate two dates:
date at 0:0:0 time
date+1day at 0:0:0 time
Then search for:
query.greaterThanOrEqualTo('createdAt', date);
query.lessThan('createdAt', datePlusOne);
This effectively gives you the range of dateT0:0:0 - dateT23:59:59.99999 inclusive, but in a safe way
If you want to use pure JavaScript:
// assuming date is the date/time to start from
date.setHours(0, 0, 0, 0);
// hours/min/sec/ms cleared
var datePlusOne = new Date(date);
datePlusOne.setDate(datePlusOne.getDate() + 1);
You can also use the moment library to make your code easier to read/maintain. This library is also used server-side in parse.com, though it is an older version.
m1 = new moment(date);
m1.startOf('day');
m2 = new moment(m1);
m2.add(1, 'day');
// convert moment back to JavaScript dates
date = m1.toDate();
var datePlusOne = m2.toDate();
Full solution using moments:
var d = new Date();
var query = new Parse.Query("TableName");
var start = new moment(d);
start.startOf('day');
// from the start of the date (inclusive)
query.greaterThanOrEqualTo('createdAt', start.toDate());
var finish = new moment(start);
finish.add(1, 'day');
// till the start of tomorrow (non-inclusive)
query.lessThan('createdAt', finish.toDate());
query.find.then(function(results) {
// use results
});
If you are looking for results, filtered by "created today", you could do this:
var moment = require("moment");
var start = moment().sod() //Start of day
var end = moment().eod() //End of day
var query = new Parse.Query("myClass")
query.greaterThanOrEqualTo("createdAt", start.format());
query.lessThan("createdAt", end.format());
query.find({...});
Of course, if you are looking for a greater timespan than "today", you would go with Timothy's answer.
This code has been tested in Parse Cloud Code with Momentjs 1.7.2

Comparing dates Java Script

I have the following scenario that I am strugling to code.
I have a valuation date that is a string that is chosen by a user from a calander popup. What I need to do is take that date and pass it into a function that works outs a second date depending on the value of that date. If the first date is more than 7 days from the first day of the month use the first day of the month else use the last day of the month. This needs to happen in client side as this date need to be displayed after they have chosen the first date.
SO far I have the below:
Function CompareDate()
{ var date1 = document.getElementById("textbox1");
var x = new date();
var year = x.getYear();
var day = x.getDay();
var thisMonthFirstDay = new Date(year, month,1)
var thisMonthLastDate = ....
var 1day = 1000*60*60*24
var date1_ms = recdate
var date2ms = thisMonthFirstDay.gettime()
if(Math.round(difference_ms/1day) > 7
{var textbox = document,getelementbyid("textbox2");
textbox.value = texbox.value + thisMonthLastDate
}
else
{
textbox.value = texbox.value + thisMonthFirstDay }
}
Any examples of how this can be done would be greatly appeciated.
Cheers
getDate() will give you the day of month (e.g. 18), so if (getDate() <= 7) { outputDate = 1; } If you're having a problem getting the last day of each month for the else statement, I generally use a 12 capacity array with hard-coded values, adding 1 to February if (year % 4 == 0).
I have managed to resolve this after a finding the parseDate() function on a fiddler site. That allowed me to convert the date from this format (31 Jan 2013) to a date and then I could just use the getDay(function) to see if the day was > 7. From there it was easy!
Thanks for above suggestions.

Simple javascript date math... not really

I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.

Categories