Date format change - javascript

I would like to change the date format in my code like that - > 19.7.2016
Could anyone help me, please?
function calcWorkingDays(fromDate, days) {
var count = 0;
var m = new Date();
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
alert(calcWorkingDays(new Date(), 4));

You need to format the dateobject to your likeness:
Extract the Day, Month and Year from your DateObject:
var month = fromDate.getUTCMonth() + 1; //months from 1-12
//January=0, February=1, etc
var day = fromDate.getUTCDate();
var year = fromDate.getUTCFullYear();
newdate = day + "." + month + "." + year;
Complete Example:
function calcWorkingDays(fromDate, days) {
var count = 0;
var m = new Date();
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
var month = fromDate.getUTCMonth() + 1;
var day = fromDate.getUTCDate();
var year = fromDate.getUTCFullYear();
newdate = day + "." + month + "." + year;
return newdate;
}
alert(calcWorkingDays(new Date(), 4));
Other possible examples are:
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"
source

You should convert date to string:
function calcWorkingDays(fromDate, days) {
var count = 0;
var m = new Date();
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate.getDate() + "." + (fromDate.getMonth()+1) + "." + fromDate.getFullYear();
}
alert(calcWorkingDays(new Date(), 4));

Related

JavaScript is returning NAN for a string '021519' on html

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

Javascript increment and decrement YYYY-MM-DD by 1 day

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>

javascript print weekend date

Hello Guys i want to show the week ending date in javascript or through some jquery calendar plugin with below functionality
It looks something like this:
Week Ending: < show weekending date in dd/MMM/YYYY format >
and then if we click on these left and right arrows it should show next weekend in same format.
kindly please suggest me if there is a plugin with similar functionality or if we can achieve this with simple javascript
Use this to get the first and last day of week.
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 firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
console.log("Week Start : "+firstday);
console.log("Weekend : "+lastday);
var date = new Date(lastday);
var formattedDate = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
console.log(formattedDate);
You can change lastday format manually using getDay(), getMonth() and getFullYear()
Try This .
var current = new Date(); // get current date
var weekstart = current.getDate() - current.getDay() +1;
var weekend = weekstart + 6; // end day is the first day + 6
var monday = new Date(current.setDate(weekstart));
var sunday = new Date(current.setDate(weekend));
<html>
<head>
<script>
function myFunction(data) {
if(data == "down")
change = change - 7;
else if(data == "up")
change = change + 7;
var someDate = new Date();
var day = someDate.getDay();
var numberOfDaysToAdd = 0;
if(day == 1) { numberOfDaysToAdd = 5; }
else if(day == 2) { numberOfDaysToAdd = 4; }
else if(day == 3) { numberOfDaysToAdd = 3; }
else if(day == 4) { numberOfDaysToAdd = 2; }
else if(day == 5) { numberOfDaysToAdd = 1; }
someDate.setDate(someDate.getDate() + numberOfDaysToAdd + change);
var dd1 = someDate.getDate();
var mm1 = someDate.getMonth() + 1;
var yy1 = someDate.getFullYear();
someDate.setDate(someDate.getDate() + 1);
var dd2 = someDate.getDate();
var mm2 = someDate.getMonth() + 1;
var yy2 = someDate.getFullYear();
var someFormattedDate = dd1 + '/'+ mm1 + '/'+ yy1 + '\n' + '&' +
dd2 + '/'+ mm2 + '/'+ yy2;
document.getElementById("showWeekends").innerHTML = someFormattedDate;
}
</script>
</head>
<body>
<button onclick="myFunction('down')"><</button>
<span id="showWeekends"></span>
<button onclick="myFunction('up')">></button>
</body>
<script>
var change = 0;
myFunction("none");
</script>
</html>

Amending the function to calculate into the new year and not return the value 12/33/2014

I need your help.
It seems that the function this_week('end') is returning a bad date of 12/33/2014 (mm/dd/yyyy) where it should properly read:
01/02/2015
function this_week(x) {
var today, todayNumber, fridayNumber, sundayNumber, monday, friday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = 1 - todayNumber;
fridayNumber = 5 - todayNumber;
if (x === 'start') {
//var start_dd = today.getDate() + mondayNumber
var start_dd = today.getDate()
var start_mm = today.getMonth() + 1
var start_yyyy = today.getFullYear()
return start_mm + '/' + start_dd + '/' + start_yyyy
}
if (x === 'end') {
var end_dd = today.getDate() + fridayNumber
var end_mm = today.getMonth() + 1
var end_yyyy = today.getFullYear()
return end_mm + '/' + end_dd + '/' + end_yyyy
}
}
What needs to be done?
You have to use Date objects when increasing or decreasing the date..
function this_week(x) {
var date, todayNumber, fridayNumber;
date = new Date();
todayNumber = date .getDay();
mondayNumber = 1 - todayNumber;
fridayNumber = 5 - todayNumber;
if (x === 'start') {
date.setDate(date.getDate()+ mondayNumber);
}
else if (x === 'end') {
date.setDate(date.getDate()+ fridayNumber);
}
var end_dd = date.getDate().toString();
end_dd = (end_dd.length == 2)?end_dd:"0"+end_dd;
var end_mm = (date.getMonth() + 1).toString();
end_mm = (end_mm.length == 2)?end_mm:"0"+end_mm;
var end_yyyy = date.getFullYear().toString();
return end_mm + '/' + end_dd + '/' + end_yyyy;
}
document.write(this_week('end'));
Note that the month code for January is 0
For a much simpler version:
function this_week(x,d) {
var d = d || new Date(),
offset = 0;
switch (x){
case 'start':
offset = 1 - d.getDay();
break;
case 'end':
offset = 5 - d.getDay();
break;
}
d.setDate(d.getDate() + offset);
return d;
}
var oE = document.getElementById('o'),
tE = document.getElementById('t');
function $log(t){ oE.innerHTML += (t || '') + "\r\n"; }
function $fmt(d){ return [d.getMonth() + 1, d.getDate(), d.getFullYear() ].map(function(v){ return v < 10 ? '0' + v : v; }).join('/'); }
function c(el){ try { var d = new Date(el.value); tE.innerHTML = 'Start: ' + $fmt(this_week('start',d)) + '; End: ' + $fmt(this_week('end',d)); } catch (e) { tE.innerHTML = 'Invalid Date'; } }
$log( 'Fixed dates' );
var ds = [
new Date(2014, 12 - 1, 29),
new Date(2015, 1 - 1, 1)
];
for (var i = 0; i < ds.length; i++){
$log( $fmt(ds[i]) + ' start » ' + $fmt(this_week('start', ds[i])) );
$log( $fmt(ds[i]) + ' end » ' + $fmt(this_week('end', ds[i])) );
}
$log();
$log( 'Based on today:' );
$log( $fmt(this_week('start')) );
$log( $fmt(this_week('end')) );
$log();
$log('::All dates in mm/dd/yyyy format::');
<pre id="o"></pre>
<hr />
<input type="text" onchange="c(this);" placeholder="try me"><button>Try</button><span id="t"></span>
Assuming that a complete week may start on sunday or on monday, this function covers both:
function this_week(start, givendate, weekStartsOnsunday) {
givendate = givendate && givendate instanceof Date ? givendate : new Date;
var today = givendate.getDay(),
isSunday = !weekStartsOnsunday && today < 1,
diff = !start
? (isSunday ? -2 : (5 - today))
: (isSunday ? -6 : (1 - today));
// set date to begin/end of week and return it formatted
return (givendate.setDate(givendate.getDate() + diff), format(givendate));
}
// format mm/dd/yyyy with leading zero's using an Array and Array.map
function format(date) {
return [ date.getDate(),
date.getMonth()+1,
date.getFullYear()
].map(function (v) {return v <10 ? '0'+v : v;})
.join('/');
}
var log = Helpers.log2Screen;
// today and week starts on monday
log('`this_week()`: ', this_week());
log('`this_week(true)`: ',this_week(true));
// given date is sunday, week starts on monday
log('`this_week(false, new Date(\'2015/01/04\'))`: ',
this_week(false, new Date('2015/01/04')), ' (week ends on sunday)');
log('`this_week(true, new Date(\'2015/01/04\'))`: ',
this_week(true, new Date('2015/01/04')), ' (week ends on sunday)');
// given date is sunday, week starts on sunday
log('`this_week(false, new Date(\'2015/01/04\'), true)`: ',
this_week(false, new Date('2015/01/04'), true), ' (week starts on sunday)')
log('`this_week(true, new Date(\'2015/01/04\'), true)`: ',
this_week(true, new Date('2015/01/04'), true), ' (week starts on sunday)');
<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>

Not getting date format using javascript

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.

Categories