what is difference between these "new Date()"s? - javascript

var today = new Date();
var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
endYear.setFullYear(today.getFullYear()); // Set year to this year
console.log("Version 1: end year full date is ", endYear);
var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
var daysLeft = Math.round(daysLeft); //returns days left in the year
console.log(daysLeft,endYear);
// when l write that code answer is 245.
var today = new Date();
var endYear = new Date(2021, 0, 0, 0, 0, 0, 0); // Set day and month
console.log("Version 2: end year full date is ", endYear);
var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
var daysLeft = Math.round(daysLeft); //returns days left in the year
console.log(daysLeft,endYear);
// but when l add only 1 ms then answer returns like 244. but how is it possible? where has 1 day gone?

That is the difference with the time you set.
To be clear,
first endYear will print Thu Dec 31 2020 23:59:59
second endYear will print Thu Dec 31 2020 00:00:00
That is the difference you see there.
I will post the complete out put I received on console here as well.
Thu Dec 31 2020 23:59:59 GMT+0530 (India Standard Time)
245.0131708912037
245
Thu Dec 31 2020 00:00:00 GMT+0530 (India Standard Time)
244.01317090277777
244
==================EDIT==================
new Date(2021, 0, 0, 0, 0, 0, 0) calculates this to Dec 31st because date is indexed from 1 and not zero. If that value is zero it computes it as the day before the 31st of December.
For example,
new Date(Date.UTC(2021, 1, 0, 0, 0, 0, 0)) will print out Sat Jan 31 2021 05:30:00 GMT+0530 (India Standard Time)
and
new Date(Date.UTC(2021, 1, -1, 0, 0, 0, 0)) will print out Sat Jan 30 2021 05:30:00 GMT+0530 (India Standard Time)

Related

JS Date cannot get the last day of month with 31 days

This month (March) has 31 days.
I want to get the last day of the month and instead of get Wed Mar 31 2021 23:59:59 I get Fri Apr 30 2021 23:59:59 look:
let d = new Date()
d.setMonth( d.getMonth() + 1) // April
d.setDate(0) // should bring the 31 of March
d.setHours(23, 59, 59, 999)
console.log(d) // Fri Apr 30 2021 23:59:59 GMT+0300 (IDT)
Why does it happen on date with 31 days?
When tried on different months every month it worked as well, for example:
let d = new Date("2021-02-25") // notice that we point to February
d.setMonth( d.getMonth() + 1)
d.setDate(0)
d.setHours(23, 59, 59, 999)
console.log(d) // Sun Feb 28 2021 23:59:59 GMT+0200 (IST)
Notice that in the second example - which is working good, we get the last day of Feb and GMT+2 (IST) and not GMT+3 (IDT)
Also notice that if I declare it like that: let d = new Date('2021-03-25') it also works good (with specific date, instead of just new Date())
It happens because April only has 30 days.
let d = new Date()
d.setMonth( d.getMonth() + 1) // Actually April 31st -> May 1st.
Try this way:
d.setMonth(d.getMonth(), 0);
second argument 0 will result in the last day of the previous month
Got it!
I set +1 for the month while the current date is 31 and what will happen is that it will jump to 31 of April which doesn't exist and the default date will be 1 in May.
So prev date of 1 in May is 30 of April.
I should set the date to 1 before doing the increment of the month, look:
let d = new Date()
d.setDate(1) // this is the change - important!
d.setMonth( d.getMonth() + 1)
d.setDate(0)
d.setHours(23, 59, 59, 999)
console.log(d) // Wed Mar 31 2021 23:59:59
That way, it will start from 1 of March, inc to 1 of April, and go prev date to last day of March.
Even that it also works, weird:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1, 0, 0, 0, 0);
var lastDay = new Date(y, m + 1, 0, 23, 59, 59, 999)
console.log(lastDay)

setMinutes not gettng expected result

I have the following js codes:
// set a date time say 2 Oct
var localTime = new Date(2016, 9, 2, 4, 0, 0);
// set time to 23:59:59
localTime.setHours(23, 59, 59, 0);
console.log(localTime); // // Sun Oct 02 2016 23:59:59 GMT+0800 (MYT), which is expected
// now minus 600 minutes, which should be 10 hours
localTime.setMinutes(-600);
console.log(localTime); // Sun Oct 02 2016 13:00:59 GMT+0800 (MYT)
When I minus 600 minutes from that time, I am expecting it to minus 10 hours which should be 13:59:59 but it's printing 13:00:59
What is that I am missing here?
Date.prototype.setMinutes does not add/remove minutes from the time you have. It sets the minutes value for your date. The argument you provide is:
minutesValue
An integer between 0 and 59, representing the minutes.

JavaScript - Weird usage of Date.getDate() for to get the days-count of a month. How does that work?

I've seen that code-technique, trick, hack (how you wanna call it) on CodeReview: https://codereview.stackexchange.com/questions/142706/take-a-specified-weekday-and-check-if-it-falls-on-the-remaining-days-of-the-cur
In the 6th line the getDate() method is used for to get the count of days of a month. Month specified as the previous parameter.
I've played around with these technique and it seems to work:
var d = new Date();
var sep = new Date(d.getYear(), (d.getMonth() + 1), 0).getDate();
var oct = new Date(d.getYear(), (d.getMonth() + 2), 0).getDate();
var nov = new Date(d.getYear(), (d.getMonth() + 3), 0).getDate();
var dec = new Date(d.getYear(), (d.getMonth() + 4), 0).getDate();
var jan = new Date(d.getYear(), (d.getMonth() + 5), 0).getDate();
console.log(d.toLocaleString('en-US', { month: 'long' }));
console.log('%s %s %s %s %s', sep, oct, nov, dec, jan);
But how is it possible that it works?
I would expect the Date-constructor to accept only valid integers.
One can give it whatever integer one likes. It doesn't throw an exception. BUT: The returned values are scrap.
var d = new Date();
var nov = new Date(d.getYear(), (d.getMonth() + 3), 31).getDate(); // November has 30 days.
console.log('%s', nov); // => 31
var nov = new Date(d.getYear(), (d.getMonth() + 3), -21).getDate(); // November has 30 days.
console.log('%s', nov); // 9
var nov = new Date(d.getYear(), (d.getMonth() + 3), 301).getDate(); // November has 30 days.
console.log('%s', nov); // 27
Can anyone with some insights explain what goes on there?
This is simply a property of the Date class, as documented on MDN:
Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.
They talk about values greater than their logical range, but the same logic applies for values lower than their range.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var d = new Date();
var nov = new Date(d.getYear(), (d.getMonth() + 3), 31).getDate(); // November has 30 days.
console.log('%s', nov); // => 31 Thu Dec 31 2016 00:00:00 GMT+0530 (India Standard Time)
var nov = new Date(d.getYear(), (d.getMonth() + 3), -21).getDate(); // November has 30 days.
console.log('%s', nov); // 9 Mon Nov 09 2016 00:00:00 GMT+0530 (India Standard Time)
var nov = new Date(d.getYear(), (d.getMonth() + 3), 301).getDate(); // November has 30 days.
console.log('%s', nov); // 27 Mon Sep 27 2017 00:00:00 GMT+0530 (India Standard Time)

Getting all occurrences of a day in month

i have the first day and last day of the month, the length of the current month i'm looking for a function that will give me all the appearances of any day in this month, i've seen some functions that gives the next occurrence but i want to be able to enter any day and see all is occurrences .. i guess it will be some kind of loop..i'm working on it as we speek but any help would be great..
$scope.recurrenceFields.by_year_day=$filter('date')($scope.fields.times.dateStart, 'yyyy');
$scope.recurrenceFields.by_month=$filter('date')($scope.fields.times.dateStart, 'M');
var correntDay = new Date();
var lastDayOfMonth = new Date(correntDay.getFullYear(), correntDay.getMonth()+1, 0);
var firstDayOfMonth = new Date(correntDay.getFullYear(), correntDay.getMonth(), 1);
function daysInMonth(month,year) {
return new Date($filter('date')($scope.fields.times.dateStart, 'yyyy'), $scope.recurrenceFields.by_month, 0).getDate();
}
Not quite sure what "all the appearances of any day in this month" means, but the following function returns all the occurrences of a particular day in a month given year, month and day number.
/* #param {number} year - calendar year
** #param {number} month - calendar month: 1-Jan, 2-Feb, etc.
** #param {number} dayNumber - day number: 0-Sunday, 1-Monday, etc.
** #returns {Array} Dates for all days in month of dayNumber
*/
function getAllDaysInMonth(year, month, dayNumber) {
var d = new Date(year, --month, 1);
var dates = [];
var daysToFirst = (dayNumber + 7 - d.getDay()) % 7;
var firstOf = new Date(d.setDate(d.getDate() + daysToFirst));
while (firstOf.getMonth() == month) {
dates.push(new Date(+firstOf));
firstOf.setDate(firstOf.getDate() + 7);
}
return dates;
}
// Return array of all Thursdays in July 2015
console.log(getAllDaysInMonth(2015, 7, 4));
// [Thu 02 Jul 2015,
// Thu 09 Jul 2015,
// Thu 16 Jul 2015,
// Thu 23 Jul 2015,
// Thu 30 Jul 2015]
// Get all Tuesdays in February 2000
console.log(getAllDaysInMonth(2000, 2, 2));
// [Tue 01 Feb 2000,
// Tue 08 Feb 2000,
// Tue 15 Feb 2000,
// Tue 22 Feb 2000,
// Tue 29 Feb 2000]
// Get all Sundays in December 2015
console.log(getAllDaysInMonth(2015, 12, 0));
// [Sun 06 Dec 2015,
// Sun 13 Dec 2015,
// Sun 20 Dec 2015,
// Sun 27 Dec 2015]
You can use this service :
angular.module('myApp.services')
.factory('dateUtils', function () {
return {
getIntervals: function (startTimestamp, endTimestamp, interval) {
if(!angular.isNumber(startTimestamp) || !angular.isNumber(endTimestamp) || !angular.isNumber(interval) || startTimestamp===0 || endTimestamp===0) {
return [];
}
var intervals = [];
var currentPeriod = startTimestamp;
while (currentPeriod <= endTimestamp) {
intervals.push(currentPeriod);
var currentPeriodDate = new Date(currentPeriod);
currentPeriodDate.setDate(currentPeriodDate.getDate() + interval);
currentPeriod = currentPeriodDate.getTime();
}
return intervals;
}
};
});
If you want all day between two dates, just use the service :
dateUtils.getIntervals(startDate, endDate, 1);

Why JavaScript Date object constructor doesn't work correctly?

Look at this code:
var date = new Date();
console.log(date);
// Tue Apr 30 2013 14:24:49 GMT+0430
var date2 = new Date(
date.getFullYear(),
date.getMonth(),
date.getDay(), 0, 0, 0, 0
)
console.log(date2)
// Tue Apr 02 2013 00:00:00 GMT+0430
I simply extracted some date from today's date, and created another date with that data, and the result is another date, not today.
What's wrong with JavaScript's Date object?
.getDay() returns the day of the week (0-6), not day of the month. (It returns 2 for Tuesday)
Use getDate() - it will return 30
getDay() returns the day of the week (from 0 to 6), not the day of the month (1-31).
the correct method is getDate():
var date = new Date();
console.log(date);
// Tue Apr 30 2013 14:24:49 GMT+0430
var date2 = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(), 0, 0, 0, 0
)
console.log(date2)
// Tue Apr 30 2013 00:00:00 GMT+0430

Categories