Last 7 days javascript - javascript

I have a report create time as 2016-05-30, now I need to get the last 7 days from the report time.How can I get using moment?
report_create_time = moment('2016-05-30').format('MMM DD, YYYY');
I see this but it gives 7 days from the current date but I want from the report_Create_time.
dateFrom = moment().subtract(7,'d').format('YYYY-MM-DD');

you can try this pure javascript
var d = new Date('2016-05-30');
var day = d.getDate() - 7;
var month = d.getMonth();
var year = d.getFullYear();
var d1 = new Date(year+"-"+month+"-"+day);
alert(d1);
https://jsfiddle.net/c6c2vur8/

Small change needed
report_create_time = moment('2016-05-30');
dateFrom = report_create_time.subtract(7,'days');
report_create_time = report_create_time.format('MMM DD, YYYY'); // if you needed this formatted date to show in your HTML
dateFrom is the day before 7 days. so we need days from dateFrom to report_create_time
If you have both the dates, you can add 1 day from dateFrom up to seven days
var dates = []
for(var i=1; i<=7; i++){
dates[i-1] = dateFrom.add('1', 'days').fotmat('MMM DD, YYYY')
}
If you don't need this way, you can subtract 1 day from report_create_time 7 times

Related

how to display the date as a day/month/year format after adding 10 days to current date

so I got this function that adds 5 days to the current date, the only problem is that the date is displayed as "Mon May 30 2022 00:16:04 GMT+0300 (Eastern European Summer Time)" I need a simple, clean format like 22/07/2002.
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
ar d = new Date();
d.setDate(d.getDate() + 10);
document.getElementById("date").innerHTML = d ;
SUGGESTION
You can use formatDate(date, timeZone, format) method to easily format date objects. See this quick sample below:
SCRIPT
function test() {
var d = new Date();
var formattedDate = Utilities.formatDate(new Date(d.setDate(d.getDate() + 5)), Session.getScriptTimeZone(), "dd/MM/yyyy")
console.log(formattedDate);
}
Demo:
date.toISOString().slice(0, 10): Convert date to string and get first 10 character.
toISOString() (2022-05-29T23:03:31.782Z to 2022-05-29)
date.split('-').reverse().join('/'): Split string by -, reverseit for formatting and convert array to a string with / separator. (2022-05-29 to 29/05/2022)
const addDays = (days) => {
let date = new Date();
date.setDate(date.getDate() + days);
date = date.toISOString().slice(0, 10);
return date.split('-').reverse().join('/');
}
const date = addDays(5);
console.log(date);
Format Date and add days to it
function formatDate(days = 10) {
const dt = new Date();
Logger.log(Utilities.formatDate(new Date(dt.getFullYear(),dt.getMonth(),dt.getDate() + days),Session.getScriptTimeZone(),"dd/MM/yyyy"));
}
Execution log
5:11:55 PM Notice Execution started
5:11:54 PM Info 03/06/2022
5:11:56 PM Notice Execution completed
Try this
// Note this wont calculate 5days ahead ,it just gives the asked format!
var today = new Date();
var dd = String(today.getDate()).padStart(2,'0');
to the current date
var mm = String(today.getMonth()+1).padStart(2,'0');
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
console.log(today);
This should work if the days overflow with the months.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Add Days to Date</title>
</head>
<body>
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
<script>
//Date class
var d = new Date();
//Returns the current day
var day = d.getDate();
//Returns the current month
var month = d.getMonth();
//Returns the current year
var year = d.getFullYear();
//New Date Class for the current date plus added days
//Days overflowing will make a new month and a new year if needed
//see "https://www.w3schools.com/js/js_dates.asp" for more info
var newDate = new Date(year, month, day+5);
//month indexes are 0-11 for Jan-Dec, so the added one is necessary
var dd = newDate.getDate();
var mm = newDate.getMonth()+1;
var yyyy = newDate.getFullYear();
//for the double digit string
dd = dd.toString().padStart(2,"0");
mm = mm.toString().padStart(2,"0");
//Date string Message
var dateString = `${dd}/${mm}/${yyyy}`;
document.getElementById("date").innerHTML = dateString;
</script>
</body>
</html>

Moment.Js date to week & year

hi I would like to use moment js to pass the week and year number and he returns me "startOf" & "endOf" Step type Week = 22 Year = 2021and I would like him to
return
startOf = 31/05/2021
endOf = 06/06/2021
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
let starDay = moment('2021').add(1, 'weeks').startOf('week').format('DD MM YYYY');
let endDay = moment('2021').add(1, 'weeks').endtOf('week').format('DD MM YYYY');

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

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

How to calculate number of day name between 2 dates in javascript

I have 2 datepickers and a list of checkboxes of week days. A user can select a start date or end date and check any checkbox day. I want to count the number of
week days between 2 days.
For example: I want to join any yoga classes then I will select start or end date and also select week day like Monday , Tuesday .
Now i want to count the number of all Mondays and Tuesdays between 2 dates
date1 = Mar 01,2016
date2 = Apr 01,2016
I want to count number of day name between these date like this:
no of sunday: 4
no of monday: 4
no of tuesday: 5 etc..
I have tried this code
var d = new Date(date1);
var now = new Date(Date.now());
var daysOfYear = [];
count = 0;
for (d ; d <= date1 ; d.setDate(d.getDate() + 1)) {
val = $("#ch_"+d.getDay());
if(val.is(':checked')){
count++;
}
}
But it gives a TypeError: d.getDay is not a function
You need to iterate between dates and check the day
First convert the dates into a date object
date1 = convertToDateObj(date1); //assuming you already have a way to parse this string to date
date2 = convertToDateObj(date2); //assuming you already have a way to parse this string to date
Now iterate throught them
var dayCount = {0:0,1:0,2:0,3:0,4:0,5:0,6:0}; //0 is sunday and 6 is saturday
for (var d = date1; d <= date2; d.setDate(d.getDate() + 1))
{
dayCount[d.getDay()]++;
}
console.log(dayCount);

Categories