Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.
Related
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
var today = new Date();
var tomorrow = today.setDate(today.getDate() + 1)
console.log(tomorrow)
1596607917318
I am getting 13 digit number after using setDate(). How can I get the date in 2 digit format?
Date outputs in JS often need some manual processing to be exactly what you want. Try this:
// Create new Date instance
var today = new Date();
var tomorrow = today;
// Add a day
tomorrow.setDate(tomorrow.getDate() + 1)
console.log(formatDateToString(tomorrow));
function formatDateToString(date) {
var dd = (date.getDate() < 10 ? '0' : '')
+ date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '')
+ (date.getMonth() + 1);
return dd + "/" + MM;
}
The Date object has different methods that you can use to get certain parts of the timestamp.
// for day-month (i.e.: Oct 31 is 31-10
let formatted = `${tomorrow.getDate()}-${tomorrow.getMonth() + 1}`
See more: https://www.w3schools.com/js/js_date_formats.asp
setDate has changed the date of today.
Therefore output today and don't assign what's returned by setDate.
var today = new Date();
today.setDate(today.getDate() + 1);
console.log(today.toLocaleDateString());
Month is zero based so getMonth() + 1 returns this month, getDate() + 1 returns tomorrow.
var fecha = new Date();
var year = fecha.getFullYear();
var mes = fecha.getMonth() + 1;
var dia = fecha.getDate() + 1;
var hora = fecha.getHours();
var minutos = fecha.getMinutes();
var segundos = fecha.getSeconds();
var output = `Date: ${dia}/${mes}/${year}`+ '\n' + `Time: ${hora}:${minutos}:${segundos}`;
console.log(output)
Nice question, I recently had to do something similar in VB. Here is a simple javascript version, based on your code:
//this gets the date today
var today = new Date();
//we add one, to get the date tomorrow
var tomorrow = today.getDate() + 1
//if tomorrow is a single digit number, we just pad it with a zero
if (tomorrow < 10)
{
tomorrow = '0' + tomorrow
}
//write to the console
console.log(tomorrow)
I need to get the date one day after another date.
I do :
$scope.date2.setDate($scope.date1.getDate()+1);
if
$scope.date1 = 2015-11-27
then
$scope.date2 = 2015-11-28
It s ok,
but when
$scope.date1 = 2015-12-02
then
$scope.date2 = 2015-11-28 (ie tomorrow)
I don't understand why...
If anyone knows..
try this instead efficient simple pure JS
var todayDate = new Date();
console.log(new Date().setDate(todayDate.getDate()+1));
so you will have that same Date type object and hence you don't need to go with moment.js
Use moment.js for this momentjs
var startdate = "2015-12-02";
var new_date = moment(startdate, "YYYY-MM-DD").add('days', 1);
var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');
alert(new_date);
alert(day + '.' + month + '.' + year);
I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var reservation_end = document.getElementById('return_date');
var dateResult = reservation_begin + loan_period;
return_date.value = dateResult;
}
USING the Suggestions made by Linus
I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var resDate = new Date(reservation_begin);
alert(resDate)
var period = loan_period;
var output = document.getElementById('return_date');
resDate.setDate(resDate.getDate() + period);
alert(period)
//return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}
As mentioned dates could be a bit tricky to handle with js.
But to just add days to a date this could be a solution?
JSBIN: http://jsbin.com/lebonababi/1/edit?js,output
JS:
var resDate = new Date('2015-02-01');
var period = 6;
var output = "";
resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
alert(output);
EDIT:
Added a new JSBin which is more consistent with the original code.
JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output
HTML:
<input id="reservationStart" type="text" value="2015-03-01" />
<br />
<input id="requestedDays" type="text" value="14" />
<br />
<a id="calculateDate" href="javascript:;">Calculate Date</a>
<br /><br /><br />
Output:
<input id="calculatedDate" type="text" />
JS:
// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);
// Click function
function returnDate(){
var reservationStart = document.getElementById('reservationStart').value,
requestedDays = parseInt(document.getElementById('requestedDays').value),
targetDate = new Date(reservationStart),
formattedDate = "";
// Calculate date
targetDate.setDate(targetDate.getDate() + requestedDays);
// Format date
formattedDate = formatDate(targetDate);
// Output date
document.getElementById('calculatedDate').value = formattedDate;
}
// Format date (XXXX-XX-XX)
function formatDate(fullDate) {
var dateYear = fullDate.getFullYear(),
dateMonth = fullDate.getMonth()+1,
dateDays = fullDate.getDate();
// Pad month and days
dateMonth = pad(dateMonth);
dateDays = pad(dateDays);
return dateYear + "-" + dateMonth + "-" + dateDays;
}
// Pad number
function pad(num) {
return (num < 10 ? '0' : '') + num;
}
As per my comment,
Split reservation_begin and use the Date constructor feeding in the
parts to create a Javascript date object. getTime will give you the
milliseconds since the Epoch. There are 86400000 milliseconds in a day, so
multiply this by loan_period. Add the two millisecond result together
and use the Date constructor with your total milliseconds to get
dateResult as a Javascript date object.
using Date.UTC but you don't have to.
function pad(num) {
return num < 10 ? '0' + num : num;
}
var reservation_begin = ('2015-02-01').split('-'),
loan_period = '5',
begin,
end;
reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
end.getUTCFullYear(),
pad(end.getUTCMonth() + 1),
pad(end.getUTCDate())
].join('-');
Why split the date string into parts? This is to avoid cross browser parsing issues.
Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.
Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.
What does pad do? It formats the month values to MM and date values to DD.
Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.
A bit confused with the third variable "reservation_end" but according to your question this solution might work.
var dateResult = new Date(reservation_begin);
dateResult.setDate(dateResult.getDate() + parseInt(loan_period));
alert(dateResult);
http://jsfiddle.net/uwfpbzt2/
Example using todays date:
var today = new Date();
today.setDate(today.getDate() + x);
where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.
EDIT
var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Assuming your date is entered in dd/mm/yyyy format as inputDate then
dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Depending on the date format your split() delimiter and array positions may be different but this is the general idea.
I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012"; // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}
I have this code:
var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();
It works, but it's format is Month, Day, Year.
I need to change it to: Day, Month Year.
So, I tried this:
var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();
Now, my change does not work. Is it that I have not done it properly or is my change right?
Thanks
I expect the correct answer is this:
var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();
This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.
var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year
or perhaps you prefer 22/05/2011
var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year
You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"