date formatting issues. js jquery - javascript

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>

Related

calculate startdate and enddate of week, yields a strange result when 1st of new month

I use the code below to calculate the start and enddate of the week based on the current date.
As i live in sweden, the first day of the week is on a monday.
if the date is 31th of august 2021 the result is 20210830-20210905
But now, when the date becomes 1st of september 2021 the result is 20210830-20210805?
How is it even possible?
I am running this locally on a firebase cloud emulator and in the firebase cloud function live, the result are the same.
function currentWeeklyId() {
const dateNow = new Date();
// First day is the day of the month
const first = dateNow.getDate() - dateNow.getDay() + 1;
const last = first + 6;
const fDay = new Date(dateNow.setDate(first));
const lDay = new Date(dateNow.setDate(last));
var firstMonth = fDay.getMonth() + 1;
if (firstMonth < 10) firstMonth = '0' + firstMonth;
var firstDay = fDay.getDate();
if (firstDay < 10) firstDay = '0' + firstDay;
var lastMonth = lDay.getMonth() + 1;
if (lastMonth < 10) lastMonth = "0" + lastMonth;
var lastDay = lDay.getDate();
if (lastDay < 10) lastDay = "0" + lastDay;
const docId = dateNow.getFullYear() + firstMonth + firstDay + "-" + dateNow.getFullYear() + lastMonth + lastDay;
return docId;
}
The problem lies on this line
const lDay = new Date(dateNow.setDate(last));
You are changing the date, but not the month. dateNow points to August month.
The lDay should reference new fDay while setting date.
const lDay = new Date(dateNow.setDate(fDay.getDate()+6))
function currentWeeklyId() {
const dateNow = new Date();
// First day is the day of the month
const first = dateNow.getDate() - dateNow.getDay() + 1;
const fDay = new Date(dateNow.setDate(first));
const lDay = new Date(dateNow.setDate(fDay.getDate() + 6))
var firstMonth = fDay.getMonth() + 1;
if (firstMonth < 10) firstMonth = '0' + firstMonth;
var firstDay = fDay.getDate();
if (firstDay < 10) firstDay = '0' + firstDay;
var lastMonth = lDay.getMonth() + 1;
if (lastMonth < 10) lastMonth = "0" + lastMonth;
var lastDay = lDay.getDate();
if (lastDay < 10) lastDay = "0" + lastDay;
const docId = dateNow.getFullYear() + firstMonth + firstDay + "-" + dateNow.getFullYear() + lastMonth + lastDay;
return docId;
}
Seems for your calculation of lastDay you need to add in the original date- as of right now you’re just setting the day of the month rather than adding.
lDay = dateNow.setDate(dateNow.getDate() + last)

How to write a method which gives me future date time in format YYYY/MM/DD 12:30:50

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;
},

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

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.

Javascript date - Leading 0 for days and months where applicable

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:
var myDate = new Date();
var prettyDate =(myDate.getFullYear() +'-'+ myDate.getMonth()) +'-'+ myDate.getDate();
This would output as:
2011-8-8
I would like it to be:
2011-08-08
The format you seem to want looks like ISO. So take advantage of toISOString():
var d = new Date();
var date = d.toISOString().slice(0,10); // "2014-05-12"
No, there is no nice way to do it. You have to resort to something like:
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
if(month <= 9)
month = '0'+month;
var day= myDate.getDate();
if(day <= 9)
day = '0'+day;
var prettyDate = year +'-'+ month +'-'+ day;
var myDate = new Date();
var m = myDate.getMonth() + 1;
var d = myDate.getDate();
m = m > 9 ? m : "0"+m;
d = d > 9 ? d : "0"+d;
var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;
...and a sample: http://jsfiddle.net/gFkaP/
You can try like this
For day:
("0" + new Date().getDate()).slice(-2)
For month:
("0" + (new Date().getMonth() + 1)).slice(-2)
For year:
new Date().getFullYear();
You will have to manually check if it needs a leading zero and add it if necessary...
var m = myDate.getMonth();
var d = myDate.getDate();
if (m < 10) {
m = '0' + m
}
if (d < 10) {
d = '0' + d
}
var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;
Yes, get String.js by Rumata and then use:
'%04d-%02d-%02d'.sprintf(myDate.getFullYear(),
myDate.getMonth() + 1,
myDate.getDate());
NB: don't forget the + 1 on the month field. The Date object's month field starts from zero, not one!
If you don't want to use an extra library, a trivial inline function will do the job of adding the leading zeroes:
function date2str(d) {
function fix2(n) {
return (n < 10) ? '0' + n : n;
}
return d.getFullYear() + '-' +
fix2(d.getMonth() + 1) + '-' +
fix2(d.getDate());
}
or even add it to the Date prototype:
Date.prototype.ISO8601date = function() {
function fix2(n) {
return (n < 10) ? '0' + n : n;
}
return this.getFullYear() + '-' +
fix2(this.getMonth() + 1) + '-' +
fix2(this.getDate());
}
usage (see http://jsfiddle.net/alnitak/M5S5u/):
var d = new Date();
var s = d.ISO8601date();
For Month,
var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
For Day,
var day = ("0" + (myDate.getDate() + 1)).slice(-2);
Unfortunately there's no built-in date-format in javascript. Either use a existing library (example http://blog.stevenlevithan.com/archives/date-time-format) or build your own method for adding a leading zero.
var addLeadingZeroIfNeeded = function addLeadingZeroIfNeeded(dateNumber) {
if (String(dateNumber).length === 1) {
return '0' + String(dateNumber);
}
return String(dateNumber);
},
myDate = new Date(),
prettyDate;
prettyDate = myDate.getFullYear() + '-' + addLeadingZeroIfNeeded(myDate.getMonth()) + '-' + addLeadingZeroIfNeeded(myDate.getDate());
EDIT
As Alnitak said, keep in mind that month i JavaScript starts on 0 not 1.
The easiest way to do this is to prepend a zero and then use .slice(-2).
With this function you always return the last 2 characters of a string.
var month = 8;
var monthWithLeadingZeros = ('0' + month).slice(-2);
Checkout this example:
http://codepen.io/Shven/pen/vLgQMQ?editors=101

Categories