Datetime comparison in JavaScript/jQuery - javascript

I have these two calendar pickers that chooses the date for you, one for arrival and one of departed.
If the user chooses a day in departed calendar that is earlier than the one in arrival calendar, the calendar picker should be either disabled or when choosen - ignore it.
For example: arrival is 2017-03-08, choosen and read in the textbox and same for departed. If I try to pick 2017-03-07 for departed, it should not allow it and not be read in the textbox.
How is this possible with javascript/jquery?
My code:
var CalendarTwo;
function onPopupTxtArrivalDateChanged(sender) { //Function that reads arrival date
var txtArrival = $("#txtArrivalDate");
var date = new Date(sender.getSelectedDate());
var textDate = date.getFullYear() + "-" + (date.getMonth() <= 9 ? "0" + (date.getMonth() + 1)
: (date.getMonth() + 1)) + "-" + (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate());
txtArrival.val(textDate);
onChange(sender, txtArrival, $("#txtDepartureDate")[0], CalendarTwo);
}
function onPopupTxtDepartureDateChanged(sender) { //Function that reads departed date
var txtDeparture = $("#txtDepartureDate");
var date = new Date(sender.getSelectedDate());
var textDate = date.getFullYear() + "-" + (date.getMonth() <= 9 ? "0" + (date.getMonth() + 1)
: (date.getMonth() + 1)) + "-" + (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate());
CalendarTwo = sender;
txtDeparture.val(textDate);
}
function onChange(sender, txt, departed, calendarTwo) { //Function that checks that arrival date and departed is equal
var txtDate = $(txt).val();
var date = new Date(txtDate);
if (departed != undefined) {
CalendarTwo = calendarTwo;
var departedDate = new Date($(departed).val());
if (departedDate < date) {
calendarTwo.setSelectedDate(date);
departed.value = txtDate;
}
}
sender.SetSelectedDate(date);
}

Related

Unable to get property 'replace' of undefined or null reference?

This code throws error:
Unable to get property 'replace' of undefined or null reference
function formatDate(dateVal) {
var date = new Date(parseInt(dateVal.replace('/Date(', '')))
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return (day.toString().length > 1 ? day : "0" + day) + "/" + (month.toString().length > 1 ? month : "0" + month) + "/" + year;
}
The value being passed to it is null and is in format like /Date(-62135596800000)/.
Well, if you pass a null value, it doesn't have any properties. Make sure you pass the correct value:
function formatDate(dateVal) {
var date = new Date(parseInt(dateVal.replace('/Date(', '')))
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return (day.toString().length > 1 ? day : "0" + day) + "/" + (month.toString().length > 1 ? month : "0" + month) + "/" + year;
}
console.log(formatDate("/Date(-62135596800000)/"));
use default parameters like this formatDate(dateVal = "" ) ,It allows you to set default values for your function parameters if no value is passed or if undefined is passed:
function formatDate(dateVal = "" ) {
var date = new Date(parseInt(dateVal.replace('/Date(', '')))
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return (day.toString().length > 1 ? day : "0" + day) + "/" + (month.toString().length > 1 ? month : "0" + month) + "/" + year;
}
Your issue seems to be that you're expecting a string like "/Date(-62135596800000)/" but are getting something else. So validate the input before calling string methods to parse it, e.g.
function formatDate(dateVal) {
// Test for string in required format
if (!/^\/Date\([+-]?\d{1,16}\)\/$/.test(dateVal)) {
return; // undefined
}
let date = new Date(parseInt(dateVal.replace('/Date(', '')))
let month = date.getMonth() + 1;
let day = date.getDate();
let year = ('000' + date.getFullYear()).slice(-4);
return (day > 9 ? day : "0" + day) + "/" +
(month > 9 ? month : "0" + month) + "/" +
year;
}
// Simple tests
['/Date(-62135596800000)/',
null,
NaN,
'sweet',
1561853541934,
'/Date(1561853541934)/'].forEach(
v => console.log(v + ': ' + formatDate(v))
);
Then in the caller, you can test if you got back a string (success) or undefined, which indicates invalid input that you'll need to deal with.

Date changes when setting value

I'm facing a strange problem, I have a function to get the current date. It may not be the best, but it's ok. I then use the function to set the value of a hidden input:
function gettoday() {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var out = (day < 10 ? '0' : '') + day + '/' +
(month < 10 ? '0' : '') + month + '/' +
d.getFullYear();
return out;
}
something.attr('value', String(gettoday()));
When I do so the date becomes 31/12/1969. The gettoday() function returns the correct date. Any ideas what could be happening? I tried debugging the call but nothing happens there. The same happens in Chrome or Firefox. Thanks!
You should set the value using val in yyyy-mm-dd format, try the following snippet
function gettoday() {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var out = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
return out;
}
$('input').val(gettoday());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date">

date formatting issues. js jquery

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>

Formatting Date in javascript [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I want date with this format : '%Y-%m-%dT%H:%M:%S+0000'. I wrote a function but still asking myself if there is not better way to do this.
This is my function :
function formatDate() {
var d = new Date();
var year = d.getMonth() + 1;
var day = d.getDate();
var month = d.getMonth() + 1;
var hour = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var date = d.getFullYear() + "-" + (month < 10 ? '0' + month : month) + "-" +
(day < 10 ? '0' + day : day) +
"T" + (hour < 10 ? '0' + hour : hour) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec) + "+0000";
return date;
}
Any ideal on how to do this with less code ?
It can be done in one line. I made two lines to make it simpler. Combine line 2 and 3.
var d = new Date();
date = d.toISOString().toString();
var formattedDate = date.substring(0, date.lastIndexOf(".")) + "+0000";
console.log(formattedDate);
Use moment.js.
moment().format('YYYY-MM-DDTh:mm:ss+0000')
JSBIN
console.log(moment().format('YYYY-MM-DDTh:mm:ss+0000'))
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
var d = new Date();
var dateString = d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+ d.getUTCDate() + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds()+"+0000";
getUTCMonth returns 0 - 11, so want to add one before you convert to string.

How to get first Monday of Month and Week in fullcalendar control

I have one case related to fullCalendar control. I am showing Days from Mon-Fri and there is Custom Button added named as Add new Appointment. When user clicks on this button we need to show First Monday date for Month view and if it is Week view we need to show 1st date(Monday) of that week. '
I have done this way till now it's working for IST time Zone but my client is CST/EST and it takes previous day. Example- on Month view if i go to Feb and click on Add new it should 02-02-2016 but it's taking 01-31-2015.
function processDateTimeForNewCalendar() {
debugger;
var mondayForWeek = common.getMondayForCurrentWeek(new Date());
var dateHeader = $('div.fc-center h2').text();
var view = $('#calendar').fullCalendar('getView');
var date, sTime, eTime;
var currentDate = new Date();
if (view.name === 'month') {
debugger;
var currentMonth = dateHeader.split(" ")[0];
var currentYear = dateHeader.split(" ")[1];
var monthInNo = common.getMonthNumberByMonthName(currentMonth);
var temp = currentDate.getDate() + "-" + currentMonth + "-" + currentYear + " " + currentDate.getHours() + ":" + currentDate.getMinutes()
var tempDate = new Date(temp);
var mondayForWeek = common.getMondayForCurrentWeek(tempDate);
if ((currentDate.getMonth() + 1) === monthInNo)
date = new Date(currentDate.getDate() + "-" + currentMonth + "-" + currentYear + " " + currentDate.getHours() + ":" + currentDate.getMinutes());
if ((currentDate.getMonth() + 1) < monthInNo || (currentDate.getMonth() + 1) > monthInNo)
date = new Date(view.intervalStart);
sTime = moment(date).format("hh:mm A");
eTime = moment(date).add(30, 'minutes').format("hh:mm A");
}
if (view.name === 'agendaWeek' || view.name === 'agendaDay') {
date = new Date(view.start);
date = moment(date).format("MM/DD/YYYY");
sTime = moment(currentDate).format("hh:mm A");
eTime = moment(currentDate).add(30, 'minutes').format("hh:mm A");
}
$(CALENDAR.ApptStartDateById).val(moment(date).format("MM/DD/YYYY"));
$(CALENDAR.ApptEndDateById).val(moment(date).format("MM/DD/YYYY"));
$(CALENDAR.ApptStartTime).timepicker("setTime", sTime);
$(CALENDAR.ApptEndTime).timepicker("setTime", eTime);
$(CALENDAR.Duration).val(calculateDuration());
$(CALENDAR.ApptStartDateById).datepicker("update", date).datepicker('fill');
$(CALENDAR.ApptEndDateById).datepicker("update", date).datepicker('fill');
}
Please help me fix this.
Thanks,
Amod
You can use $('calendar selector').fullCalendar('getView').start to get the starting date of your current view;
I have done it in other way by finding the first Day of the Month and checks if it is sunday. If it is then add +1 day. Check the code below-
function getFirstDayOfMonth(d) {
d.setMonth(d.getMonth(), 1);
// if sunday add +1 day
if (d.getDay() === 0)
d.setDate(d.getDate() + 1, 1);
return d;
}
Hope, this is the alternate solution for finding first day of month using fullCalendar.

Categories