getYear() in JavaScript returns 118 [duplicate] - javascript

This question already has answers here:
Why does Javascript getYear() return a three digit number?
(14 answers)
getMonth in javascript gives previous month
(6 answers)
Closed 4 years ago.
I need to calculate the date of the last Monday that before the latest weekend. Having used what I believe to be the most common Stack Overflow suggestions I have the following code:
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const newNewDate = new Date(newDate.getTime());
console.log(newNewDate);
const day = newNewDate.getDate();
const month = newNewDate.getMonth();
const year = newNewDate.getYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
It returns the year as 118 and the month as 5 which are ... not that Monday I need. newNewDate, on the other hand is the last Monday. I was wondering what causes it. I am aware that there are too many reassignments that are not needed. Please help.

Whatever you are doing is perfect only, the only mistake is you are using getMonth() and getYear() and misunderstanding them.
date.getMonth() gives you months ranging from 0-11. So 5 is actually June month.
date.getYear() this method returns the year minus 1900, so actual is 118+1900=2018, instead you can use date.getFullYear() which will return 2018
Also, you don't need so many steps.
the function can be simply stopped with newDate as given below
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const day = newDate.getDate();
const month = newDate.getMonth() + 1;
const year = newDate.getFullYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
This will give "the year is 2018 the month is 6"
Hope this helps.

Related

Javascript How to increase Month when Date is over today month [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 1 year ago.
i really stuck at this date. Let say today is 01 20 2021, and i want to add 14 day later to get expired date. so for the expired date should be 02 03 2021, but i only get 01 03 2021. Can anyone help me on this. Thanks
this is my code
var today = new Date();
var monthIndex = today.getMonth()+1;
var year = today.getFullYear();
var addday = new Date(new Date('1.20.2021').getTime()+(14*24*60*60*1000));
var nextDay = addday.getDate();
var nextMonth = monthIndex;
console.log('day',day)
return nextMonth+'.'+nextDay+'.'+year
//the return that I want is 2.03.2021
You didnt update the value for monthIndex. You must use:
var nextMonth = addday.getMonth()+1;
Just use Date.setDate function for this.
// new Date('1.20.2021') => Jan 20 2021
const dateStr = '1.20.2021';
const [mm, dd, yyyy] = dateStr.split('.');
const today = new Date(yyyy, +mm-1, dd);
// add 14 days
const newDate = new Date(new Date(today).setDate(today.getDate() + 14));
console.log(`Today: ${today}`);
console.log(`New Date: ${newDate}`);
console.log(newDate.getMonth() + 1 + '.' + newDate.getDay() + '.' + newDate.getFullYear());

Get the date from day number of week Javascript

I have a model in my database that contains an array called "AvailableDays" [0...6]. 0 = Sunday & 6 = Saturday. I am looking to convert this day number of the week to the date of day in the current week.
For example, this is the logic broken down
Retrieve the list of available days (const availableDays = [0,2,4,6])
Get the current DATE (const today = new Date('2021-08-20');)
Covert day numbers to dates (output =['15-08-2021', '17-08-2021', '19-08-2021', '21-08-2021'])
What you can do is get the day-of-the-week from the given Date instance and work out the offset from your available day.
Then subtract that offset in days from the given date to produce your result.
const transformDate = (date, day) => {
const offset = date.getDay() - day
const d = new Date(date)
d.setDate(d.getDate() - offset)
return d
}
const availableDays = [0,2,4,6]
const today = new Date("2021-08-20")
console.log(availableDays.map(day => transformDate(today, day)))
Was able to solve this myself. I am now able to wrap this into a availableDates.map() and return an array of dates using the below logic.
var availableDay = 0
var d = new Date(),
day = d.getDay(), // 0 ... 6
calcAvailableDay = day-availableDay,
diff = d.getDate() - calcAvailableDay,
output = new Date(d.setDate(diff));
console.log(output)
You can generate all the days in weeks and then get the dates using availableDays.
const getWeekDays = (current) => {
current.setDate((current.getDate() - current.getDay() - 1));
return Array.from({ length: 7 }, (_, i) => {
current.setDate(current.getDate() + 1)
return new Date(current).toLocaleDateString('en-CA');
});
},
today = new Date('2021-08-20'),
weekDays = getWeekDays(today),
availableDays = [0, 2, 4, 6],
availableDates = availableDays.map(day => weekDays[day]);
console.log(availableDates);
JavaScript getDay method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So what you have to do is connect this index with your availableDays values.
Logic
Get current date, month, year and the index of todays date.
Loop through the availableDays array, and create new dates with the difference between the current day calculated with getDay value and the day value specified in your array.
Make use of some logic to reperesent those date object in specified format. I took support from this post to format your date string.
const availableDays = [0,2,4,6];
const today = new Date();
const currentDay = today.getDay();
const currentDate = today.getDate();
const currentMonth = today.getMonth();
const currentYear = today.getFullYear();
formatDateToString = (date) => String(date.getDate()).padStart(2, '0') + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + date.getFullYear();
const output = availableDays.map((day) => formatDateToString(new Date(currentYear, currentMonth, currentDate - (currentDay - day))));
console.log(output);

Difference of two Dates shows 6 days too much

const oldDate= new Date('2019-07-19T19:20:00');
const newDate = new Date('2020-07-19T19:20:00'); // 1 year later
let timeDiff = new Date(newDate.getTime() - oldDate.getTime());
const years = timeDiff.getFullYear()-1970;
const months = timeDiff.getUTCMonth();
const days = timeDiff.getUTCDay(); // why 6 days ????
console.log(days);
I try to calc the difference between two dates and show it as years, months, days.
I really don't know if there is something wrong in the code or why are there 6 days as a difference? Should it be not 0?
const oldDate= new Date('2019-07-19T19:20:00');
const newDate = new Date('2020-07-19T19:20:00'); // 1 year later
let timeDiff = new Date(newDate.getTime() - oldDate.getTime());
const years = timeDiff.getFullYear()-1970;
const months = timeDiff.getUTCMonth();
const days = timeDiff.getUTCDay(); // why 6 days ????
As per MDN:
Date.prototype.getUTCDate()
Returns the day (date) of the month (1–31) in the specified date according to universal time.
Date.prototype.getUTCDay()
Returns the day of the week (0–6) in the specified date according to universal time.
So you likely wanted .getUTCDate(), not .getUTCDay().

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Get date of exactly 6 days ago from today in JS [duplicate]

This question already has answers here:
How to subtract days from a plain Date?
(36 answers)
Closed 3 years ago.
Thank you in advance
I would like your help with getting 'days ago' from a particular date. I don't want to use any library.
Although I have tried moment JS.
Use getDate() and subtract the number of days from it
var d = new Date();
d.setDate(d.getDate() - 6);
console.log(d);
First, make a new Date with your date:
const date = new Date('December 17, 1995 03:24:00');
Second, subtract 6 days like so:
date.setDate(date.getDate() - 6);
Third, use date.toString() :
console.log(date.toString());
You question title and description contradict with each other.
The following function that return number of days ago can help if this is what you need:
function getDaysAgo(date, now = new Date()) {
//first calculating start of the day
const start = now.setHours(0, 0, 0, 0);
//then calculating difference in miliseconds
const diff = start - date.getTime();
//finally rounding to a bigger whole days
const result = Math.ceil(diff/(1000*60*60*24));
//as a bonus returning today/yesterday/future when necessary
if (result < 0) {
return 'in future';
}
if (result === 0) {
return 'today';
}
return result === 1 ? 'yesterday' : result + ' days ago';
}
For example getDaysAgo(new Date(Date.parse('2019-9-28 23:59')), new Date(Date.parse('2019-9-30 10:59'))) returns 2 days ago.
It is a simple function that returns a new desire past date.
function getNthDate(nthDate){
let date = new Date();
return new Date(date.setDate(date.getDate() - nthDate))
}
Live example

Categories