Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers
Related
var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}
Try this code:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
To compare it one time falls between a time interval on the same day use: -
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));
You can use new Date().getTime() to get the number of milliseconds since the Unix Epoch. So that you can compared the date/time with the result from this function. You can do sth like that:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
I would suggest to check if your checkDateTime is greater than your startDateTime and less then endDateTime.
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}
Here is yet another option which adds the method directly to the Date prototype:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
This way, with any date you have var someDate, you can just call someDate.inRange(startDate, endDate). Sometimes, however, messing with the native prototypes can come back to haunt you if not careful. If so, having a separate function as answered by the others is very good.
Lastly, it's very important that the date strings are formatted properly before creating the Date objects, otherwise you'll encounter Invalid Date a lot. I hope this helps.
I'm using cleandersonlobo:date-picker-materialize package to input the date and I want to display an alert("expired") if the input date is less than the current date.
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < new Date()) {
$('#myModal1').modal('hide');
alert("Job expired");
}
Try following code,
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < $strToday ) {
$('#myModal1').modal('hide');
alert("Job expired");
}
A toMidnight function that sets the time of a date to midnight and by doing so removes time as a factor for your comparison:
function toMidnight(date) {
var midnight = arguments.length > 0 ? new Date(date) : new Date();
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
midnight.setMilliseconds(0);
return midnight;
}
Then you can compare your date like this:
toMidnight($dtDate) < toMidnight()
Ok I cant get my head round this, ive looked at so many posts on SF but cant figure it out.
I need to campare server time with hardcorded time.
i have try this
var breackfastCutOffTime = "5:30";
var lunchCutOffTime = "10:00";
var dinnerCutOffTime = "17:00";
var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
document.getElementById("lunch").disabled = true;
}else if(serverTime >= dinnerCutOffTime){
document.getElementById("dinner").disabled = true;
}
}
I know this cant compare because time are in text format.Some one pleace help me to compleate this.
You can write a function which converts Time(hh:mm) in minutes(mm) only. Then you can compare two times and do your operations accordingly.
pseudocode:
function convert(string time) int {
//split the time by ':'
//convert the string hh,mm to int hour,mm
//calculate total minutes
//return total minutes
}
Refer Date Api for more info.
Below is your modified code. I have commented few lines. Modify according to your logic
Fiddler link
//var breackfastCutOffTime = "5:30";
var breackfastCutOffTime = new Date();
breackfastCutOffTime.setHours(5);
breackfastCutOffTime.setMinutes(30);
//var lunchCutOffTime = "10:00";
var lunchCutOffTime = new Date();
lunchCutOffTime.setHours(10);
lunchCutOffTime.setMinutes(00);
//var dinnerCutOffTime = "17:00";
var dinnerCutOffTime = new Date();
dinnerCutOffTime.setHours(17);
dinnerCutOffTime.setMinutes(00)
var serverTime = new Date();
//var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
//if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
console.log("breackfastCutOffTime");
//document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
//document.getElementById("lunch").disabled = true;
console.log("lunchCutOffTime");
}else if(serverTime >= dinnerCutOffTime){
//document.getElementById("dinner").disabled = true;
console.log("dinnerCutOffTime");
}
//}
Explanation:
Instead of converting the Date format to string i am creating new instance of the date for each cutoff time and setting desired time to that object.
Finally compare the date objects directly.
Note: The Date objects are set according to your timezone.
You can pass the breackfastCutOffTime,lunchCutOffTime and dinnerCutOffTime to the below function and it will return true if they are equal to or greater than current time.
function compareTime(timeToCompare) {
var currentDate = new Date();
var tempDate = new Date();
var timeToCompareArray = timeToCompare.split(":");
tempDate.setHours(timeToCompareArray[0]);
tempDate.setMinutes(timeToCompareArray[1]);
if (tempDate >= currentDate) {
return true;
} else {
return false;
}
}
I have a requirement where i need to find the date entered in the textfield should not be less than currentdate and future date should not exceed exactly date after 1 year from the eentered date.I have coded for former one but i later requirement i could not do it.
I have posted code for checking less than current date here. Please let me know for checking if the date entered exceed the date after 1 year.
var currentDate = new Date();
var nextDate = new Date();
function checkLessThanCurrentDate() {
//var dateEntered = arguments[0]; -->Will have date that come form textfield
var day = dateEntered.split("/")[0];
var month = dateEntered.split("/")[1];
var year = dateEntered.split("/")[2];
//--->Logic for chekcing date less than current date
if ((year < currentDate.getFullYear() || (month - 1 < currentDate.getMonth() &&
year <= currentDate.getFullYear()) || ((day < currentDate.getDate()) && (month -
1 <= currentDate.getMonth()) &&
(year <= currentDate.getFullYear())))) {
return true;
}
else {
return false;
}
}
Here's how to get the date one year from now:
var now = new Date();
var oneYear = new Date();
var oneYear.setYear(now.getFullYear() + 1);
if (dateEntered > oneYear) {
// logic
}
I think this should work for both your requirements:
function isValidDate(dateToCheck)
{
return isLessThanYearFromToday(dateToCheck) && dateToCheck >= new Date();
}
function isLessThanYearFromToday(dateToCheck)
{
var yearFromToday = new Date();
yearFromToday.setFullYear(yearFromToday.Year + 1);
return dateToCheck <= yearFromToday;
}
you need to use .getTime() method. .getTime() return the time in millisonds
var toDayDate = new Date();
var enteredDate = new Date('06/09/2015'); // mm/dd/yyyy formate
if(toDayDate.getTime()<enteredDate.getTime() && toDayDate.getTime()+(365*24*60*60*1000) > enteredDate.getTime()){
alert();
}
DEMO
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";
}