I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.
Related
I have written below method for this but it will fail when the current date will be 31.
I need to check if date is 31 it should return me 1st date of next month. Any help would be appreciated
getFutureDateTime: function () {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate() + 1;// to get current date remove "+1"
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
},
It looks like you're trying to get the next day as a string. Your best bet is to let the Date object do the rollover between months and years for you, like this:
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hour = dt.getHours();
var minute = dt.getMinutes();
var second = dt.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
},
Note that if you're doing this in any vaguely modern environment, you can use padStart on the string (and padStart is easily polyfilled):
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var dateTime =
year.toString().padStart(2, "0") +
"/" +
month.toString().padStart(2, "0") +
"/" +
day.toString().padStart(2, "0") +
" " +
hour.toString().padStart(2, "0") +
":" +
minute.toString().padStart(2, "0") +
":" +
second.toString().padStart(2, "0");
return dateTime;
},
You could give yourself a utility function for the padding, to avoid repeating yourself:
function padZero2(val) {
return String(val).padStart(2, "0");
}
// ...
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var dateTime =
padZero2(year) +
"/" +
padZero2(month) +
"/" +
padZero2(day) +
" " +
padZero2(hour) +
":" +
padZero2(minute) +
":" +
padZero2(second);
return dateTime;
},
Similarly, if you use an ES2015 template literal, it may be a bit clearer:
getFutureDateTime: function () {
const dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
const dateTime = `${padZero2(year)}/${padZero2(month)}/${padZero2(day)} ${padZero2(hour)}:${padZero2(minute)}:${padZero2(second)}`;
return dateTime;
},
You don't need to have that complex function, look at this:
function getFutureDateTime() {
const regex = /(^[0-9-]+)(t)([^Z.]+)/i;
const date = new Date();
const isoFutureDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).toISOString();
const matches = iso.match(regex);
return matches[1] + ' ' + matches[3];
}
m= require("moment")
console.log(m().add("months",2).format("YYYY/MM/DD HH:MM:SS"))
use momentjs why to reinvent wheel when you already have some nodejs library for that you can change months to days , years etc to add days,houts,years etc instead of month
https://momentjs.com/guides/#/warnings/add-inverted-param/
You sould probably add an if statement before adding the '0' to test if day==32 => day = 1 and month = month+1
getFutureDateTime: function () {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate() + 1;// to get current date remove "+1"
if (day==32){
day = 1;
month = month + 1;
}
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
},
I have a formatted date as a string '021519' using javascript which return NAN on display in html.
Note I have a xslt using the javascript.
var newDate = '';
var formatedDate = new Date(date);
var year = formatedDate.getFullYear().toString();
var month = (1 + formatedDate.getMonth()).toString();
if(parseInt(month) < 10)
{
month = "0" + month;
}
var day = formatedDate.getDate().toString();
if(dateFormat == '1')
{
newDate = month + day + year.substr(2,4);
}
else
{
newDate = month + day + year;
}
var newLeftStart3 = parseInt(startPosition) - 1;
var newLeftEnd3 = newLeftStart + newDate.length;
var newRightStart3 = parseInt(endPosition) - newDate.length;
var newRightEnd3 = newRightStart + newDate.length;
if(alignment == '1')
{
addendaSpace = addendaSpace.substr(0, newLeftStart3) + newDate + addendaSpace.substr(newLeftEnd3);
}
if(alignment == '2')
{
addendaSpace = addendaSpace.substr(0, newRightStart3) + newDate + addendaSpace.substr(newRightEnd3);
}
newDate is displaying as NaN i hope this code helps.
I usually format dates in javascript this way:
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1; //Months are zero based
var year = d.getFullYear();
console.log(date + "-" + month + "-" + year);
Date formatting issues after July.the date shown is a weekly format. any help will be highly appreciated.the date is working fine just that not working as expected
$(document).ready(function () {
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first));
startDate = ((startDate.getMonth() + 1) < 10 ? '0'
: '')
+ (startDate.getMonth() + 1)
+ "/"
+ ((startDate.getDate() < 10 ? '0' : '') + startDate
.getDate())
+ "/"
just change this code
var endDate = new Date(startDate);
endDate.setDate(startDate.getDate() + 6);
You can check below working code.
$(document).ready(function () {
//var curr = new Date('2020-02-29'); // for leap
var curr = new Date();// get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var startDate = new Date(curr.setDate(first));
var endDate = new Date(startDate);
endDate.setDate(startDate.getDate() + 6);
startDate = ((startDate.getMonth() + 1) < 10 ? '0'
: '')
+ (startDate.getMonth() + 1)
+ "/"
+ ((startDate.getDate() < 10 ? '0' : '') + startDate
.getDate())
+ "/"
+ startDate.getFullYear();
endDate = ((endDate.getMonth() + 2) < 10 ? '0' : '')
//this might have some flaws if i make it to 2 it works but this is short term fix and will break again
+ (endDate.getMonth() + 1)
+ "/"
+ ((endDate.getDate() < 10 ? '0' : '') + endDate
.getDate())
+ "/"
+ endDate.getFullYear();
document.getElementById("ok").innerHTML = startDate;
document.getElementById("napa").innerHTML = endDate;
$(".next")
.click(
function () {
document.getElementById("tabletbody").innerHTML = "";
var startdt = new Date($('#ok')
.text());
startdt.setDate(startdt
.getDate() + 7);
document.getElementById("ok").innerHTML = (getDateFormat(startdt));
var enddt = new Date($('#napa')
.text());
enddt
.setDate(enddt
.getDate() + 7);
document.getElementById("napa").innerHTML = (getDateFormat(enddt));
updateCompass();
return false;
});
function getDateFormat(d) {
var month = ((d.getMonth() + 1) < 10 ? '0' : '')
+ (d.getMonth() + 1);
var dd = (d.getDate() < 10 ? '0' : '')
+ d.getDate();
return month + "/" + dd + "/" + d.getFullYear();
}
$(".previous").click(function () {
document.getElementById("tabletbody").innerHTML = "";
var startdt = new Date($('#ok').text());
startdt.setDate(startdt.getDate() - 7);
$('#ok').text(getDateFormat(startdt));
var enddt = new Date($('#napa').text());
enddt.setDate(enddt.getDate() - 7);
$('#napa').text(getDateFormat(enddt));
updateCompass();
return false;
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="ok"></div>
<div id="napa"></div>
I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>
How to add a day (or 2 days) to date 31.07.2012 and return result in format dd.MM.yyyy (same format as input date)?
The best way would be to use the javascript date object. The date object in javascirpt is initialized as mm/dd/yyyy or as Date(year,month-1, date). That is,
dateString = "31.07.2012"
dateSplit = dateString.split('.')
date = new Date(dateSplit[2], dateSplit[1]-1, dateSplit[0])
date.setDate(date.getDate()+2)
newDateString = ((date.getDate() > 10) ? date.getDate() : ("0" + date.getDate())) + "." + ((date.getMonth()+1 > 10) ? date.getMonth()+1 : ("0" + (date.getMonth()+1))) + "." + (date.getFullYear())
month-1 is used in Date(year,month-1, date) because months start with 0
The result will be
"02.08.2012"
var numDaysToAdd = 2;
var inputDateString = "31.07.2012";
var resultDate = stringToDate(inputDateString);
resultDate.setDate( resultDate.getDate()+numDaysToAdd );
var result = dateToString( resultDate );
alert(result);
function stringToDate( aString )
{
var dateArray = aString.split(".");
return new Date(dateArray[2],dateArray[1]-1,dateArray[0]);
}
function dateToString( aDate )
{
var date = aDate.getDate();
date = (date > 9) ? date : "0"+date.toString();
var month = aDate.getMonth()+1;
month = (month > 9) ? month : "0"+month.toString();
var year = aDate.getFullYear();
return (date+"."+month+"."+year);
}
/**
* Format date (2012.08.31)
*/
Date.prototype.format = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '.' + (mm[1]?mm:"0"+mm[0]) + '.' + (dd[1]?dd:"0"+dd[0]); // padding
}
/**
* Increase current time
*/
Date.prototype.increase_days = function(days) {
this.setTime(this.getTime() + (days * (1000 * 60 * 60 * 24)));
return this;
}
//usage:
var date = new Date();
date.increase_days(2);
console.log(date.format());
assuming inputDateString format is dd.mm.yyyy
function addDaysToDate (inputDateString ,noOfDays ){
var myDate=dateString.split(".");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
var dateInMilliSec = new Date(newDate).getTime();
var addDaysToTime = new Date(dateInMilliSec + (86400000 * noOfDays));
var dd = addDaysToTime.getDate();
var MM = addDaysToTime.getMonth()+1;
var yyyy = addDaysToTime.getFullYear();
return dd+"."+MM+"."+yyyy;
};
This will do it for you
var d = "31.07.2012";
d = d.split(".");
date = new Date(d[2],d[1]-1,d[0]);
date.setDate(date.getDate() + 2);
document.body.innerHTML += (date.getDate() + "." + date.getMonth() + "." + (date.getFullYear()));