Get last week date with jQuery/Javascript - javascript

I'm trying to get the last week date in JavaScript, without the time.
So for example, 10-02-2012, instead of 10-02-12 13:34:56 GMT.
Is there an easy solution out there for this?
Thank you!
Edit:
I'm trying to make this dynamic, so that the resulting variable is always one week before the current date. Here's what I've done to calculate the today variable, if this helps or can be used!
var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
alert(today)

I prefer something like this
​
function getLastWeek() {
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);
console.log(lastWeekDisplay);
console.log(lastWeekDisplayPadded);
And if you're using jQuery UI, you can do this instead of the manual steps to build the string
var lastWeekDisplay = $.datepicker.formatDate('mm/dd/yy', getLastWeek());
Or for today
var todayDisplay = $.datepicker.formatDate('mm/dd/yy', new Date());

var firstDay = new Date("2009/10/02");
var previousweek= new Date(firstDay.getTime() - 7 * 24 * 60 * 60 * 1000);
Check out this link. It will help:- http://code.google.com/p/datejs/

We can't have a javascript date question answered without mentioning Moment.js.
moment().subtract('days', 7).format('MM-DD-YYYY')

Possible without external dependencies
new Date().setDate(new Date().getDate() - 7)

If you really want to create this from a full timestamp like 10-02-12 13:34:56 GMT, you might want to do this:
var time = '10-02-12 13:34:56 GMT';
document.write(time.substr(0,7));

use this code to subtract any number of days as i have selected 9 it will give last 10 days result including today
var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(9, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;

function getLastWeek() {
let today = new Date();
let day = today.getDay();
let t = day-1;
let monday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 7); //monday from last week
let sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 1); //sunday from ast week
return [monday, sunday];
}
var last_week = getLastWeek();

Related

Current Date converted to 10 days before and 10 days after

I have this code where I convert the current date to this format 2020-08-20 . But how do I alter it to give me the date 10 days from today and 10 days before today.
eg today is 2020-08-20 I am trying to get 10 days from today 2020-08-30
This is my code
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
It's a little bit tricky. First set the hours from the date to 12 for avoiding problems with summer/wintertime-changing. Then use getDate add 10 for the extra days and setDate with the new value. Now you have a value in milliseconds, generate out of this a new date to get an dateobject. For the second date subtract 20 days because the original date was changed by the action before and do all other the same.
Format the output for the dates with getFullYear, getMonth and getDate
. Because month is handled in JS from 0 to 11 add 1 month. Months and days could be 1-digit but you want it 2 digits, so add before the string "0" and get the last 2 chars of it with slice.
Do the format for both dates and return them as array.
const dateConverter = (dateIn) => {
dateIn.setHours(12);
let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
return [strFor10Days, strIn10Days];
}
let today = new Date();
console.log(dateConverter(today));
Try this
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd);
console.log(dateConverter(today));
var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract);
console.log(dateConverter(today));
I would suggest you to use the moment library but you still want plain javascript
const convert = (date) => {
const pastDate = new Date(date)
pastDate.setDate(pastDate.getDate() - 10);
const futureDate = new Date(date)
futureDate.setDate(futureDate.getDate() + 10);
return { pastDate, futureDate }
}
call convert function with any date.
This code will help you
Reference JavaScript calculating date from today date to 7 days before
for after 10 days just just convert the - to +
const dateConverter = (dateIn) => {
var dates ={};
var days = 10; // Days you want to subtract
for(let i=0;i<days;i++){
var date = dateIn;
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day = last.getDate();
var month= last.getMonth()+1;
var year= last.getFullYear();
dates[i] = year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
return dates
}
var today = new Date();
console.log(dateConverter(today));
I've been messing around that before as well.
But on this Stack Overflow you can find a really good answer:
Add days to JavaScript Date
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
This is the code taken from that post.
For subtracting days, just replace the "+ days" with "- days"
Hope this solved your problem!
You can convert all the dates to timestamp and then simply calculate with them:
const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))

how to Add 1 year to startdate to get the end date in javascript

want a output like below
if Start Date is "01-03-2016" the End date should be "28-02-2017"
if Start Date is "10-04-2016" the End date should be "09-04-2017"
I tried below code
if (dat <= 31 && dat >= 1 && month <= 12 && month >= 1) {
var expiryDate = new Date(n1, month - 1, dat);
expiryDate.setFullYear(expiryDate.getFullYear() + 1);
var day = ('0' + expiryDate.getDate()).slice(-2);
var month1 = ('0' + (expiryDate.getMonth() + 1)).slice(-2);
var year = expiryDate.getFullYear();
var month = getMonthName(month1);
var wholeenddate = day + "-" + month + "-" + year;
but it's not produce desired output.Please Help to solve it.
Add 364 days to your date
For example
var d = new Date("2016-03-01");
d.setDate(d.getDate()+364); //outputs 28-02-2017
and
var d = new Date("2016-04-10");
d.setDate(d.getDate()+364); //outputs 09-04-2017
or Just add 1 year and sub 1 day.
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
Now it will match your output just the same even for leap year :)
Demo
var d = new Date("2016-03-01");
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
document.body.innerHTML += d.toString();
document.body.innerHTML += "<br>";
d = new Date("2016-04-10");
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
document.body.innerHTML += d.toString();
There's a convenient library to help with this sort of thing - moment.js (14k zipped).
var startDate = moment('01-03-2016', 'DD-MM-YYYY');
console.log(startDate.format('DD-MM-YYYY'));
var endDate = startDate.clone();
endDate.add(1, 'years').subtract('1', 'days');
console.log(endDate.format('DD-MM-YYYY'));
3 ways to do this.
// Add hours
var today = new Date();
today.setHours(today.getHours()+24*364);
// Add days
var nextyearDate = new Date();
nextyearDate.setDate(today.getDate()+364);
// More reliable way : Add year & subtract a day.. Hope this works...! Works for 01/01/2016
var nextDate = new Date();
nextDate.setYear(nextDate.getFullYear()+1);
nextDate.setDate(nextDate.getDate()-1);

How to add one month to a date here?

I have two date variables. The first one defaults to last friday. Based on this date I'm trying to add a month to it. When I try the following code, it does not seem to work.
var StartDate = new Date()
var DayOfWeek = 5;//friday
StartDate.setDate(StartDate.getDate() + (dayOfWeek - 7 - StartDate.getDay()) % 7);
This does not seem to work.
var EndDate = new Date(StartDate)
EndDate.setDate(EndDate.getMonth() + 7)
The reason it isn't working is you have to set the month not the date.
Change your end date code to be:
var EndDate = new Date(StarteDate);
var x = 1;
EndDate.setMonth(EndDate.getMonth() + x);
Here's a reference on setMonth http://www.w3schools.com/jsref/jsref_setmonth.asp
You can add a month by doing this:
In general:
var b = new Date();
var a = new Date(new Date().setMonth(b.getMonth()+1)); //<< this line
alert(a);
Your code:
var StartDate = new Date();
var dayOfWeek = 5;
StartDate.setDate(StartDate.getDate() + (dayOfWeek + 7 - StartDate.getDay()) % 7);
var EndDate = new Date(StartDate)
EndDate.setMonth(EndDate.getMonth() + 1);
alert(EndDate); //remove...
JS Fiddle DEMO with your code

Adding a week to date javascript

I have a JSfiddle which I am trying to add a week onto a date. The date is outputting incorrect date when I try to add six days.
fiddle
code for adding a week
var endDate = new Date(date || Date.now()),
eMonth = '' + (monthNames[endDate.getMonth()]),
eDay = '' + (endDate.setDate(endDate.getDate() + 6)),
eYear = endDate.getFullYear();
Try this,
var endDate = new Date(date || Date.now());
var days = 6;
endDate.setDate(endDate.getDate() + days);
var eMonth = '' + (monthNames[endDate.getMonth()]),
eDay = '' + endDate.getDate(),
eYear = endDate.getFullYear();
Working Demo
Give this a try,
var endDate = new Date(date || Date.now());
endDate.setTime(startDateObj.getTime() + (1000 * 60 * 60 * 24 * 7));
var newDate = endDate.getFullYear()+"-"+(endDate.getMonth() + 1)+"-"+endDate.getDate();
eDay = '' + (endDate.getDate() + 6)
Remove setDate() function and change $("#startDate").text(startDate) to show value in span tag
var now = new Date().getTime();
var oneWeek = 6*24*60*60*1000;
var newDate = now+oneWeek;
alert(new Date(newDate));
this should do the work
You can also use the get/set Time methods:
var today = new Date();
var plusOneWeek = new Date();
plusOneWeek.setTime( today.getTime()+(7*24*3600*1000) ); //add 7 days
See the doc about getTime() on MDN

Javascript days +/- from today

For a datepicker I need two dates:
from: today - 7 days,
to: today + 7 days.
I get a currentDate with:
var toDay = new Date();
var curr_date = toDay.getDate();
var curr_month = toDay.getMonth();
curr_month++;
var curr_year = toDay.getFullYear();
var toDay = (curr_month + "/" + curr_date + "/" + curr_year);
How to get 7 days+ and 7 days- dates ? With corresponding month!
As per comment, You can use following code
var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
var nextWeekDate = ((myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear());
myDate = new Date();
myDate.setDate(myDate.getDate() -7 );
var prevWeekDate = ((myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear());
Modified Demo
Pretty simple:
nextWeek.setDate(toDay.getDate() + 7);
lastWeek.setDate(toDay.getDate() - 7);
Javascript saves a date as the number of milliseconds since midnight on january 1st 1970. You can get this time by calling "getTime()" on the Date object. You can then add 7X24X60X60X1000 to get 7 days later, or substract them for 7 days earlier represented in milliseconds. Then call Date.setTime() again.
edit: both these other methods involving getDate() get unpredictable when you are around the start or end of a month.
You can also extend your javascript Date object like this
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.substractDays = function(days) {
this.setDate(this.getDate() - days);
return this;
};
//then
var dateDiff=7;
var toDay = new Date();
var futureDay= new Date(toDay.addDays(dateDiff));
var prevDay = new Date(toDay.substractDays(dateDiff*2)); // substracted 14 daysbecause 'toDay' value has been incresed by 7 days
Hope this helps.
You can add /subtract like following
var fdate= new Date();
var numberofdayes= 7;
fdate.setDate(fdate.getDate() + numberofdayes);
(Not sure whether you are asking that or not)
Then you can format it in dd/mm/yyyy using getDate(), getMonth() and getFullYear().
(Don't forget to add 1 to fdate.getMonth())
var formateddate = fdate.getDate()+ '/'+ fdate.getMonth()+1 + '/'+ fdate.getFullYear();

Categories

Resources