Working with Dates in Google Apps Script - date

What I am trying to do here is this - I want to give index to only the workdays in each week.
So, if in a week, Monday and Wednesday are holidays, then Tuesday should get 1, Thursday should get 2, Friday should get the index 3. Otherwise, in a normal week without any holidays, Monday should get 1, Tuesday 2, Wednesday 3, and so on ...
Here is the code I have written (I haven't coded in years now, so please pardon the crude approach)
Sheet 'Holidays' contains a list of holidays in the column B starting from row 2
Variable date is the date for which I want to find out the index for
Variable dayOfTheWeek is the number of day of 'date' counted from last Sunday, so if date is a Monday, dayOfTheWeek is 1; if date is Tuesday, dayOfTheWeek is 2, and so on ...
function indexOfWorkdayOfTheWeek (date, dayOfTheWeek, lastSundayDate)
{
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var activeCell = activeSheet.getActiveRange();
var activeRow = activeCell.getRowIndex();
var activeColumn = activeCell.getColumn();
var count = 1;
for (var j = 1; j < dayOfTheWeek; j++)
{
var date2 = lastSundayDate.valueOf() + j*86400;
Logger.log('Date ' + j + ' is:' + date2);
Logger.log('Last Sunday is:' + lastSundayDate);
if (holidayOrNot(date2) == true)
{
}
else
{
count = count + 1;
}
}
return count;
}
function holidayOrNot(date2)
{
var holidaysSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Holidays');
var listOfHolidays = holidaysSheet.getSheetValues(2, 2, 95, 1);
var isDateMatch = false;
for (var k = 0; k < 90; k++)
{
if (date2 == listOfHolidays[k].valueOf())
{
isDateMatch = true;
break;
}
else
{
continue;
}
}
return isDateMatch;
}
I think the problem is two-fold here:
The date2 calculation isn't working for some reason (var date2 = lastSundayDate.valueOf() + j*86400;)
The function holidayOrNot is returning false, no matter what, even if it encounters a holiday ... the condition date2 == listOfHolidays[k] isn't working for some reason...
Help would be appreciated!

maybe this method below could help you in your calculations, it returns an integer corresponding to the day of the year so if you apply this to your holidays days and compare to the days of interest it could be a good way to find matches.
here it is, just add these lines outside of any function in your script (so you can use it anywhere) then use it like this :
var d = new Date().getDOY();
Logger.log(d)
Here the method :
Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}

Assuming that lastSundayDate is being passed around correctly, I see a glaring problem:
lastSundayDate.valueOf().
valueOf() on Date objects returns the primitive value... it looks like you're going for adding a day to the date (86400 seconds * j)? I can't tell what the logic is supposed to be here. But the valueOf() date2 is definitely giving you an integer something like: 1384628769399 (see here).
What you really want to accomplish is something like Date.getDay(), or something similar so that you can add hours, days, etc. to the original Date. This is likely the source of all your problems.
What you can do is read the Mozilla Developer Network documentation on Date objects to see all of the functions on Dates and their uses. You can greatly simplify what you're trying to do by using these functions, instead of doing abstract operations like j * 86400.
It should also be noted that you can do simple operations such as the following, to add 4 hours to the current Date (time):
var myDate = new Date();
Logger.log(myDate); // ~ console.write
var laterDate = new Date(myDate.setHours(myDate.getHours() + 4));
Logger.log(laterDate); // ~ console.write
which gives the following:
[13-11-16 14:13:38:947 EST] Sat Nov 16 14:13:38 GMT-05:00 2013
[13-11-16 14:13:38:954 EST] Sat Nov 16 18:13:38 GMT-05:00 2013
Working with dates can be tricky - but it's always best to use the simplest methods that are available, which are built into the Date objects themselves. There are also numerous other libraries that provide extended functionality for Dates such as Date js.
If you're still running into your problem after attempting to try using methods I displayed above, please run your script and post both the Execution Transcript and the content of the Logger so that I can help you narrow down the issue :)

Related

When I filter by date using .setHours to remove the time, the time is then lost in the filter [duplicate]

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.
The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.
The ==, !=, ===, and !== operators require you to use date.getTime() as in
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
to be clear just checking for equality directly with the date objects won't work
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.
For the curious, date.getTime() documentation:
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
Compare < and > just as usual, but anything involving == or === should use a + prefix. Like so:
const x = new Date('2013-05-23');
const y = new Date('2013-05-23');
// less than, greater than is fine:
console.log('x < y', x < y); // false
console.log('x > y', x > y); // false
console.log('x <= y', x <= y); // true
console.log('x >= y', x >= y); // true
console.log('x === y', x === y); // false, oops!
// anything involving '==' or '===' should use the '+' prefix
// it will then compare the dates' millisecond values
console.log('+x === +y', +x === +y); // true
The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.
Below you find an object with three functions:
dates.compare(a,b)
Returns a number:
-1 if a < b
0 if a = b
1 if a > b
NaN if a or b is an illegal date
dates.inRange (d,start,end)
Returns a boolean or NaN:
true if d is between the start and end (inclusive)
false if d is before start or after end.
NaN if one or more of the dates are illegal.
dates.convert
Used by the other functions to convert their input to a date object. The input can be
a date-object : The input is returned as is.
an array: Interpreted as [year,month,day]. NOTE month is 0-11.
a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.
.
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert:function(d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
The relational operators < <= > >= can be used to compare JavaScript dates:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 < d2; // true
d1 <= d2; // true
d1 > d2; // false
d1 >= d2; // false
However, the equality operators == != === !== cannot be used to compare (the value of) dates because:
Two distinct objects are never equal for either strict or abstract comparisons.
An expression comparing Objects is only true if the operands reference the same Object.
You can compare the value of dates for equality using any of these methods:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
* note: d1 == d2 returns false as described above
*/
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1) == Number(d2); // true
+d1 == +d2; // true
Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. Both Number function and unary + operator call the valueOf() methods behind the scenes.
By far the easiest method is to subtract one date from the other and compare the result.
var oDateOne = new Date();
var oDateTwo = new Date();
alert(oDateOne - oDateTwo === 0);
alert(oDateOne - oDateTwo < 0);
alert(oDateOne - oDateTwo > 0);
Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...
Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them...
1. you have 2 string values you get from an input and you'd like to compare them, they are as below:
var date1 = '01/12/2018';
var date2 = '12/12/2018';
2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date(), I just re-assign them for simplicity of explanation, but you can do it anyway you like:
date1 = new Date(date1);
date2 = new Date(date2);
3. Now simply compare them, using the > < >= <=
date1 > date2; //false
date1 < date2; //true
date1 >= date2; //false
date1 <= date2; //true
Compare day only (ignoring time component):
Date.prototype.sameDay = function(d) {
return this.getFullYear() === d.getFullYear()
&& this.getDate() === d.getDate()
&& this.getMonth() === d.getMonth();
}
Usage:
if(date1.sameDay(date2)) {
// highlight day on calendar or something else clever
}
I no longer recommend modifying the prototype of built-in objects. Try this instead:
function isSameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth();
}
console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));
N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.
e.g.
> (new Date('Jan 15 2021 01:39:53 Z')).getDate() // Jan 15 in UTC
14 // Returns "14" because I'm in GMT-08
what format?
If you construct a Javascript Date object, you can just subtract them to get a milliseconds difference (edit: or just compare them) :
js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true
Note - Compare Only Date Part:
When we compare two date in javascript. It takes hours, minutes and seconds also into consideration.. So If we only need to compare date only, this is the approach:
var date1= new Date("01/01/2014").setHours(0,0,0,0);
var date2= new Date("01/01/2014").setHours(0,0,0,0);
Now: if date1.valueOf()> date2.valueOf() will work like a charm.
The simple way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
SHORT ANSWER
Here is a function that return {boolean} if the from dateTime > to dateTime Demo in action
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
function isFromBiggerThanTo(dtmfrom, dtmto){
return new Date(dtmfrom).getTime() >= new Date(dtmto).getTime() ;
}
console.log(isFromBiggerThanTo(from, to)); //true
Explanation
jsFiddle
var date_one = '2013-07-29 01:50:00',
date_two = '2013-07-29 02:50:00';
//getTime() returns the number of milliseconds since 01.01.1970.
var timeStamp_date_one = new Date(date_one).getTime() ; //1375077000000
console.log(typeof timeStamp_date_one);//number
var timeStamp_date_two = new Date(date_two).getTime() ;//1375080600000
console.log(typeof timeStamp_date_two);//number
since you are now having both datetime in number type
you can compare them with any Comparison operations
( >, < ,= ,!= ,== ,!== ,>= AND <=)
Then
if you are familiar with C# Custom Date and Time Format String this library should do the exact same thing and help you format your date and time dtmFRM whether you are passing in date time string or unix format
Usage
var myDateTime = new dtmFRM();
alert(myDateTime.ToString(1375077000000, "MM/dd/yyyy hh:mm:ss ampm"));
//07/29/2013 01:50:00 AM
alert(myDateTime.ToString(1375077000000,"the year is yyyy and the day is dddd"));
//this year is 2013 and the day is Monday
alert(myDateTime.ToString('1/21/2014', "this month is MMMM and the day is dd"));
//this month is january and the day is 21
DEMO
all you have to do is passing any of these format pacified in the library js file
You can use this code:
var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');
var firstDate=new Date();
firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);
var secondDate=new Date();
secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);
if (firstDate > secondDate)
{
alert("First Date is greater than Second Date");
}
else
{
alert("Second Date is greater than First Date");
}
And also check the MDN article for the Date class.
function datesEqual(a, b)
{
return (!(a>b || b>a))
}
var date = new Date(); // will give you todays date.
// following calls, will let you set new dates.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
var yesterday = new Date();
yesterday.setDate(...date info here);
if(date>yesterday) // will compare dates
BEWARE THE TIMEZONE
A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy functions for translating to and from strings in the "local" timezone. If you want to work with dates using date objects, as everyone here is doing, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, particularly when you create your midnight UTC Date object.
Most of the time, you will want your date to reflect the timezone of the user. Click if today is your birthday. Users in NZ and US click at the same time and get different dates. In that case, do this...
// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));
Sometimes, international comparability trumps local accuracy. In that case, do this...
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));
Now you can directly compare your date objects as the other answers suggest.
Having taken care to manage timezone when you create, you also need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...
toISOString()
getUTCxxx()
getTime() //returns a number with no time or timezone.
.toLocaleDateString("fr",{timezone:"UTC"}) // whatever locale you want, but ALWAYS UTC.
And totally avoid everything else, especially...
getYear(),getMonth(),getDate()
Via Moment.js
Jsfiddle: http://jsfiddle.net/guhokemk/1/
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA,"DD/MM/YYYY");
var momentB = moment(dateTimeB,"DD/MM/YYYY");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("11/07/2015", "10/07/2015"));
The method returns 1 if dateTimeA is greater than dateTimeB
The method returns 0 if dateTimeA equals dateTimeB
The method returns -1 if dateTimeA is less than dateTimeB
Just to add yet another possibility to the many existing options, you could try:
if (date1.valueOf()==date2.valueOf()) .....
...which seems to work for me. Of course you do have to ensure that both dates are not undefined...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....
This way we can ensure that a positive comparison is made if both are undefined also, or...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....
...if you prefer them not to be equal.
If following is your date format, you can use this code:
var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
//...
}
It will check whether 20121121 number is bigger than 20121103 or not.
Subtract two date get the difference in millisecond, if you get 0 it's the same date
function areSameDate(d1, d2){
return d1 - d2 === 0
}
Say you got the date objects A and B, get their EPOC time value, then subtract to get the difference in milliseconds.
var diff = +A - +B;
That's all.
One way to compare two dates is to use the dates.js library.
The Date.compare(Date date1, Date date2) method that returns a number which means the one of following result:
-1 = date1 is less than date2.
0 = values are equal.
1 = date1 is greater than date2.
Performance
Today 2020.02.27 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
Conclusions
solutions d1==d2 (D) and d1===d2 (E) are fastest for all browsers
solution getTime (A) is faster than valueOf (B) (both are medium fast)
solutions F,L,N are slowest for all browsers
Details
In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE
function A(d1,d2) {
return d1.getTime() == d2.getTime();
}
function B(d1,d2) {
return d1.valueOf() == d2.valueOf();
}
function C(d1,d2) {
return Number(d1) == Number(d2);
}
function D(d1,d2) {
return d1 == d2;
}
function E(d1,d2) {
return d1 === d2;
}
function F(d1,d2) {
return (!(d1>d2 || d2>d1));
}
function G(d1,d2) {
return d1*1 == d2*1;
}
function H(d1,d2) {
return +d1 == +d2;
}
function I(d1,d2) {
return !(+d1 - +d2);
}
function J(d1,d2) {
return !(d1 - d2);
}
function K(d1,d2) {
return d1 - d2 == 0;
}
function L(d1,d2) {
return !((d1>d2)-(d1<d2));
}
function M(d1,d2) {
return d1.getFullYear() === d2.getFullYear()
&& d1.getDate() === d2.getDate()
&& d1.getMonth() === d2.getMonth();
}
function N(d1,d2) {
return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );
}
// TEST
let past= new Date('2002-12-24'); // past
let now= new Date('2020-02-26'); // now
console.log('Code d1>d2 d1<d2 d1=d2')
var log = (l,f) => console.log(`${l} ${f(now,past)} ${f(past,now)} ${f(now,now)}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
p {color: red}
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
Results for chrome
In order to create dates from free text in JavaScript you need to parse it into the Date object.
You could use Date.parse() which takes free text and tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.
Once you have a date, as other people have pointed out, you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function
var input_date="2015/04/22 11:12 AM";
var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime = new Date(Date.parse(input_date));
if (inputDateTime <= currentDateTime){
//Do something...
}
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0'+hours : hours ;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours+":"+minutes+ ' ' + ampm;
return date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
(date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
date.getDate()) + " " + strTime;
}
An Improved version of the code posted by "some"
/* Compare the current date against another date.
*
* #param b {Date} the other date
* #returns -1 : if this < b
* 0 : if this === b
* 1 : if this > b
* NaN : if a or b is an illegal date
*/
Date.prototype.compare = function(b) {
if (b.constructor !== Date) {
throw "invalid_date";
}
return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ?
(this>b)-(this<b) : NaN
);
};
usage:
var a = new Date(2011, 1-1, 1);
var b = new Date(2011, 1-1, 1);
var c = new Date(2011, 1-1, 31);
var d = new Date(2011, 1-1, 31);
assertEquals( 0, a.compare(b));
assertEquals( 0, b.compare(a));
assertEquals(-1, a.compare(c));
assertEquals( 1, c.compare(a));
I usually store Dates as timestamps(Number) in databases.
When I need to compare, I simply compare among those timestamps or
convert it to Date Object and then compare with > <if necessary.
Note that == or === does not work properly unless your variables are references of the same Date Object.
Convert those Date objects to timestamp(number) first and then compare equality of them.
Date to Timestamp
var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp
Timestamp to Date
var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);
Before comparing the Dates object, try setting both of their milliseconds to zero like Date.setMilliseconds(0);.
In some cases where the Date object is dynamically created in javascript, if you keep printing the Date.getTime(), you'll see the milliseconds changing, which will prevent the equality of both dates.
Let's suppose that you deal with this 2014[:-/.]06[:-/.]06 or this 06[:-/.]06[:-/.]2014 date format, then you may compare dates this way
var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';
parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false
As you can see, we strip separator(s) and then compare integers.
My simple answer for this question
checkDisabled(date) {
const today = new Date()
const newDate = new Date(date._d)
if (today.getTime() > newDate.getTime()) {
return true
}
return false
}
If both of your dates come in the format "YYYY-MM-DD", you can skip the Date object and compare strings directly.
This works because of how the strings are compared in JS
let date1 = '2022-12-13';
let date2 = '2022-02-13';
console.log(`${date1} > ${date2}`, date1 > date2);
console.log(`${date1} < ${date2}`, date1 < date2);
console.log(`${date1} == ${date2}`, date1 == date2);

Use the first day of the month as 1(integer)

I'm trying to build my first app using flutter framework. The app is about my "End of Year Challenge". It started from 1st Sept 2019 and will last till the end of this year.
What I'm trying to achieve is - I want to display the current day number of the challenge period. eg: 1st Sept is Day 1, 30th Sept is Day 30 and 1st Oct is Day 31 and so on.
I'm trying to get the first day of Sept and assign it to 1. Then using a loop I want the app to update the day to the current day. The loop will stop once the current day equals to 122 (as this would be the last day of the challenge)
Here's the screenshot of the UI
final firstSeptember = DateTime.utc(2019, DateTime.september, 1);
static const totalNumberOfDays = 122;
int noOfDay(){
int dayOne = firstSeptember.day; // I'm just trying codes, IDK the actual code/business logic
return dayOne;
}
In function you'd use
int noOfDay(){
var todayDate = DateTime.now();
final firstSeptember = DateTime.utc(2019, DateTime.september, 1);
var difference = todayDate.difference(firstSeptember);
return difference.inDays + 1;
}
Explanation:
Get today's date
var todayDate = DateTime.now();
You already have start date which is
final firstSeptember = DateTime.utc(2019, DateTime.september, 1);
All you need to do is subtraction.
var difference = todayDate.difference(firstSeptember);
int daysCompleted = difference.inDays + 1;

Get Every Tuesday of the month with Coldfusion

I'm currently working with jquery FullCalendar plugin to create a specific calendar.
One of my tasks I have to work out is how to get any given specific day for the month.
I'm currently using Coldfusion 10 for the server side so I'm wondering is there any specific way of getting every instance of a Tuesday into an array of dates?
Ideally I would like to do this on the server side and populate the calendar plugin.
My issue is primarily trying to source every specific day of a calendar month.
Any advice greatly appreciated.
The firstXDayOfMonth() UDF on CFLlib allows you to find the first of a given day-of-week in a given month. From there you just need to loop from that date adding 7 each iteration until the month is no long the selected month.
theMonth = month(now());
startDate = firstXDayOfMonth(3, theMonth, year(now()));
tuesdays = [];
for (date=startDate; month(date) == theMonth; date +=7){
arrayAppend(tuesdays, dateAdd("s",0, date)); // this just converts date from a number back to a date
}
writeDump(tuesdays);
Update:
Actually the approach for that UDF on CFLib is terrible. Use this variation instead:
function firstXDayOfMonth(dayOfWeek,month,year){
var firstOfMonth = createDate(year, month,1);
var dowOfFirst = dayOfWeek(firstOfMonth);
var daysToAdd = (7 - (dowOfFirst - dayOfWeek)) MOD 7;
var dow = dateAdd("d", daysToAdd, firstOfMonth);
return dow;
}
I'll update the UDF on cflib a bit later: I need to write some decent unit tests for it first, and am a bit busy # the moment.
The Short Version:
At this time, there is not a function in CF that gets all the Tuesdays. But here's an easy way to do it:
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1
var dayOfWeekArray = []; // This is the outcome.
// loop through each day of the month adding the target days to the array.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, loopingDate );
}
}
dayOfWeekArray is an array of every Tuesday of a month.
More Detail:
Your title and post seem to conflict as far as what you're looking for, so I'm going to stick with the title, since that's why I came here...
Here's what you can do to find all the Tuesdays in a month:
Create a date Object
Loop through the days in the target month using the date Object
If the current day is Tuesday, add it to an array
Boom, you got all the Tuesdays of a month in an array
Here's the code I used (cfscript):
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var dayOfWeekArray = [];
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1. Do a quick writeDump in the loop if you're not sure.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, datePart( "d", loopingDate );
// ArrayAppend( dayOfWeekArray, loopingDate ); - use this if you'd rather have the whole date object
}
}
This gives you dayOfWeekArray which will be the date of each Tuesday of a particular month. For instance, this month (Jan 2019) will be [1, 8, 15, 22, 29]. You can change this to be the entire date object if you want - that's what I did in the short version at the top.

Bootstrap Datepicker defaults to 1900's when entered with 2 digit year

I am using a datepicker in a modal window in my Bootstrap application. I am using the original Datepicker from Stefan Petre. I built it where it works in a desktop and mobile using a mouse and it works fine.
Recently I had a user request to allow it to also work with a keyboard. I removed the readonly property to allow the user to enter a date in the input field. The date-format is set to 'mm/dd/yyyy'.
When I enter a date like today for example like this "12/11/13" then it will default to 1913. This isn't a huge deal as I could just train the users to use 4 digits, but I would rather just have it default to this century.
Note: This only seems to happen for the date-format with a 4 digit year. This also seems to happen in the same manner in the newer forks of Stefan's code.
Note: I am using Bootstrap 2.0.4. I am testing with Firefox.
Here is what it looks like:
In JavaScript, set the datepicker's assumeNearbyYear attribute to true, like this:
$("#dp").datepicker({
assumeNearbyYear: true
});
This happens because the Bootstrap datepicker is using JavaScript Date objects. When you create a new Date object and pass in a two digit year it will output 1900+year (see Why does Javascript evaluate a 2-digit year of 00 as 1900 instead of 2000?)
You could try to tweak the datepicker source code, but that might be too complicated.
From what I can see on http://www.eyecon.ro/bootstrap-datepicker/ there is no option to set a range for the selectable dates, but you could change the format to use two digit years.
On your screenshot I can see, that you are using the datepicker for "Arrival Date" which I assume is in the future. On the website there is an example on how to disable dates in the past.
I hope that helps.
UPDATE
I have written an event handler for your problem which should do the trick.
Javascript on http://jsfiddle.net/pCYbd/1/
$("#dp").datepicker();
$("#dp").on("keyup", function(e) {
var date, day, month, newYear, value, year;
value = e.target.value;
if (value.search(/(.*)\/(.*)\/(.*)/) !== -1) {
date = e.target.value.split("/");
month = date[0];
day = date[1];
year = date[2];
if (year === "") {
year = "0";
}
if (year.length < 4) {
newYear = String(2000 + parseInt(year));
$(this).datepicker("setValue", "" + month + "/" + day + "/" + newYear);
if (year === "0") {
year = "";
}
return $(this).val("" + month + "/" + day + "/" + year);
}
}
});
CoffeeScript on http://jsfiddle.net/pCYbd/2/
$("#dp").datepicker()
$("#dp").on "keyup", (e) ->
value = e.target.value
if value.search(/(.*)\/(.*)\/(.*)/) != -1
date = value.split("/")
month = date[0]
day = date[1]
year = date[2]
year = "0" if year == ""
if year.length < 4
newYear = String(2000 + parseInt(year))
$(#).datepicker("setValue", "#{month}/#{day}/#{newYear}")
year = "" if year == "0"
$(#).val("#{month}/#{day}/#{year}")
My JavaScript skills are not the best, but this should work.
Updating bootstrap-datepicker.js as shown in this post solved it for me https://github.com/eternicode/bootstrap-datepicker/pull/1461/commits/2ea16adad27cbc4d4dfa20b924addfb480e5b036
yyyy: function(d,v){
if (format.parts.indexOf('yyyy') > -1 && v < 1000) v = 2000+v; // this line ***
return d.setUTCFullYear(v);
},
I'm using bootstrap-datepicker v1.5.1 and if you look around line 1741 where it does the year mapping, you will notice this:
yyyy: function (d, v) {
return d.setUTCFullYear(v);
},
yy: function (d, v) {
return d.setUTCFullYear(2000 + v);
},
When you specify that the control uses a four year date "yyyy", it will only do the return d.setUTCFullYear(v);, which will get you the previous century that JavaScript gives you. When you specify that it use the two year date "yy", it will do the correct 2000+ that you need for the current century.
So if you want the correct two year date to be 2016, 2017, etc., you need to set your datepicker to use the "yy" like so:
$('#tbPurchaseDate').datepicker({
format: 'mm/dd/yy',
autoclose: true,
todayBtn: 'linked',
todayHighlight: true,
orientation: 'bottom auto'
});
Or you can change the "yyyy" setting in the bootstrap-datepicker.js to match the "yy" version, but then you'd have to remember to do that every time you update the datepicker js file via nuget. It's much easier to just change your format setting.
Of course, if you want the full 4 digit year to display in the control, then you might want to try one of the elaborate fixes listed here or just set the "yyyy" to what the "yy" is in the js file.
Or just update your code to the latest version (1.6.4 right now) and "yyyy" and "yy" are the same and you use assumeNearbyYear: true as noted in another answer here.
For me, the best solution was to customize parseDate function in bootstrap-datepicker.js file directly. Inside a function, there is variable setters_map with yyyy property which I modified a bit. Here is my solution:
yyyy: function(d,v) {
if (v.toString().length == 2 && v <= 30) {
v = 2000 + parseInt(v);
}
return d.setUTCFullYear(v);
},
In my case it was needed to convert only years that are less or equals 30.
In the update function of bootstrap-datepicker.js I added this block of code:
var str = this.element.prop('value');
var defaulted = false;
if (str.lastIndexOf("/") >= 0 && (str.match(/\//g) || []).length == 2)
{
var yr = str.substring(str.lastIndexOf("/") + 1);
if (yr.length <= 2)
defaulted = true;
}
if (this.date.getFullYear() < 2000 && defaulted) {
this.date.setFullYear(this.date.getFullYear() + 100);
}
right before the viewdate is set on this line:
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
It will work 100% if you update below two line in UTCDate() of bootstrap-datepicker.js core file:
function UTCDate(){
/* Date defaulted date from 2000 if entered date year less than 4 degit*/
if(arguments!=null && arguments[0].toString().length<4)
arguments[0] = 2000 + arguments[0];
return new Date(Date.UTC.apply(Date, arguments));
}

How to get a list of days or a number of days in a month with GWT?

What is counter part of this code in GWT ?
public int returnAllDaysOf(2012,6){
Calendar calendar = Calendar.getInstance();
calendar.set(2012, Calendar.FEBRUARY, 1);
int daysOfFeb = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return daysOfFeb;
}
Thanks in advance for your help.
I want to get the number of days of a month in the client side. I searched Google and StackOverFlow but didn't get anything.
for example Feb has 29 days, Match has 31 days and so on ...
I don't know a direct way, but you can calculate this value by adding one month to your date, and then calcualting the difference in days:
final Date myDate = ...;
final Date copyOfDate = CalendarUtil.copyDate(myDate);
CalendarUtil.addMonthsToDate(copyOfDate, 1);
final int daysBetween = CalendarUtil.getDaysBetween(myDate, copyOfDate);
Note: This even works if myDate is something like 2012-01-31. copyOfDate is then 2012-03-02 (because february doesn't have 31 days), and the result is correct again.
"Cheating" way to do it:
int daysInCurrentMonth = new Date(year-1900, month+1, 0).getDate();
I.E.
int daysInJanuary2014 = new Date(114, 1, 0).getDate();
basically set the Date object to the 0th day of the NEXT month, then get the day of the month.
NOTE: Date(int year, int month, int date) expects year=calendarYear-1900 (i.e. 2014=114) and month is 0-based (i.e. January would be month 0)
and yes, I know this constructor is deprecated, but I still use it.
DateField dfMois = new DateField();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dfMois.getValue());
Date date = dfMois.getValue();
Date dateCopy = dateFin;
dateCopy.setDate(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
if(date.getMonth() == Calendar.FEBRUARY + 1){
date.setDate(31 - dateCopy.getDate());
date.setMonth(date.getMonth()-1);
}
else{
date.setDate(dateCopy.getDate());
}
dfMois.setValue(date);
In your code... it work.