Adding a week to date javascript - 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

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))

javascript date format yyyy-mm-dd HH:MM:ss [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I have facing an issue in javascript date format all dates in this format yyyy-mm-dd HH:MM:ss
My Code:
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var current = currentdate.toLocaleTimeString();
var previous = prevdate.toLocaleTimeString();
var first = firstdate.toLocaleTimeString();
console data
console.log(previous); //10:28:24 PM
console.log(current); //10:58:24 PM
console.log(first); //11:28:24 PM
I try this , how can i pass previous and first date
var Currentdate=dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
console.log("Currentdate"); //2020-05-07 22:58:11
Expected Output Date Format: yyyy-mm-dd HH:MM:ss
previous date: 2020-05-07 22:28:11 // date before 30min
current date: 2020-05-07 22:58:11 // current date
first date: 2020-05-07 23:28:11 // date after 30min
What should i do? can anyone help?
You should use currentdate.toLocaleString() instead, as toLocaleTimeString()
returns a string with a language sensitive representation of the time portion of this date
toLocaleString
toLocaleTimeString
Use toLocaleString instead of toLocaleTimeString
Hi please try th following function:
function getTime(){
var date = new Date();
console.log(GetFormattedDate(date));
}
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
in your case
function getTime(){
var date = new Date();
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
console.log(GetFormattedDate(prevdate));
console.log(GetFormattedDate(currentdate));
console.log(GetFormattedDate(firstdate));
}
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
regards
You need to use toLocaleString
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var options = { hour12: false };
var current = currentdate.toLocaleString('en-US', options);
var previous = prevdate.toLocaleString('en-US', options);
var first = firstdate.toLocaleString('en-US', options);
current = current.replace(/\//g, '-');
previous = previous.replace(/\//g, '-');
first = first.replace(/\//g, '-');
console.log(`current: ${current}`);
console.log(`previous: ${previous}`);
console.log(`first: ${first}`);

Get time from datetime format

I'm getting this date format from back-end: 1970-01-01T10:59:00Z
How can I get the time from it with JavaScript and put it in this input:
<input type="time" ng-model='content.time' />
Thanks for your help!
You could use the getHours(), getMinutes() and getSeconds() function and concatenate the values.
var result = document.getElementById("result");
var dateTime = new Date();
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
var seconds = new Date().getSeconds();
result.innerHTML = hours + ":" + minutes + ":" + seconds;
<p id="result"></p>
var date = new Date($scope.content.time);
var converted = date.getHours() + ":" + date.getMinutes();
console.log(converted);
This might help you:
var dt = new Date();
var tm = dt.getUTCHours();
For UTC.
Also you can use:
new dt.getHours()
new dt.getMinutes()
var date = new Date("1970-01-01T10:59:00Z");
var converted = date.toLocaleString();
console.log(converted);
Then you'd just assign the converted value to the model.
With angular, and not just vanilla javascript/DOM manipulation, in your controller js:
var dateTime=<referenceToDataRetrievedFromBackEnd>;
/*Format the date you've retrieved*/
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
var seconds = new Date().getSeconds();
var formattedTimeString=hours + ":" + minutes + ":" + seconds
/*This is the part that actual ties the retrieved and reformatted data to the view*/
$scope.content.time=formattedTimeString;
In your controller add this function
var parseDateTime = function (input) {
vars = input.split('T');
date = vars[0].split('-');
time = vars[1].split(':');
//return date in 'yyyy-MM-dd H:i:s'
return date[0] + '-' + date[1] + '-' + date[2] + ' ' + time[0] + ':' + time[1] + ':00';
}
Then you can use it with your datetime
var dateTime = DATE_RECEIVED_FROM_BACKEND;
$scope.content.time = parseDateTime(dateTime);
Hope this helps :)
place this code in the controller where after the data u receive from backend
var d = new Date("1970-01-01T10:59:09Z");//pass the object which have ur date
$scope.content.time=d.getHours() + ":" + d.getMinutes()+":"+ d.getSeconds();

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

Get last week date with jQuery/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();

Categories

Resources