JavaScript Check Date not today or in the past - javascript

JavaScript Check Date not today or in the past.
var c = '10 JUN 2010'; // this is the format of the date coming in.
var temp = new Array();
temp = c.split(' ');
var x = new Date ( temp[1]+" "+temp[0]+", "+temp[2] );
if (x.getTime() > getDate()) {
alertstring = alertstring + '\n\nDEBUG CODE: 1 ' + x + '\n\n';
}
I cannot change the format coming in.

Looks like you 99% have it. Here it is with a modified if condition:
var c = '10 JUN 2010'; // this is the format of the date coming in.
var temp = new Array();
temp = c.split(' ');
var x = new Date ( temp[1]+" "+temp[0]+", "+temp[2] );
if (x.getTime() > (new Date().getTime())) {
...
}

Update this line:
// Get current date and time
var today = new Date();
// strip time to compare to the parse date
if (x.getTime() > new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime()) {
// this date has not happened yet.
alertstring = alertstring + '\n\nDEBUG CODE: 1 ' + x + '\n\n';
}

Try to put in constructor the number of month
Instead of string .
Instead of June put 6.

Related

Uncaught TypeError: getFullYear is not a function

I keep getting the error "Uncaught TypeError: date3.getFullYear is not a function"
I have a date variable in both SQL and JS format (passed from another function as arguments):
min1 - in SQL format. [Like - '2017-08-13 0:0:00']
mindate - in JS format. [Like - 'Sun Aug 13 2017 00:00:00 GMT+0530 (India Standard Time)' ]
I am using these variables to create a new date variable called 'date3'. I have tried the following:
var date2 = min1.split(' ')[0]; // should give me '2017-08-13'
date3 = new Date(date2);
AND,
var date3 = new Date();
date3 = mindate;
AND,
var date3 = mindate;
AND,
var Y = parseInt(min1.split(' ')[0].split('-')[0]); // 2017
var M = parseInt(min1.split(' ')[0].split('-')[1]) - 1; // 7
var D = parseInt(min1.split(' ')[0].split('-')[2]); // 13
var date3 = new Date(Y,M,D);
And when I console.log the date3, it gives the correct date. But when I do a getFullYear() on date3, it gives the error: "Uncaught TypeError: getFullYear is not a function"
I have tried everything and nothing seems to work. (I even read some other similar questions, and some answers were saying its because 'date' is a 'moment' object, but I don't understand what it means and how it can help resolve this).
UPDATE:
Here's how I am using the getFullYear function. I have tried two things:
datestring = date3.getFullYear() + '-' + (date3.getMonth()+1) + '-' + (date3.getDate());
AND
var y = date3.getFullYear(),
m = date3.getMonth() + 1, // january is month 0 in javascript
d = date3.getDate();
Am using this inside a 'for' loop, and the date3 was created just above the loop as follows:
var date3 = new Date(Y,M,D);
console.log(date3);
for (k=1; k<=x; k++) {
var y = date3.getFullYear(),
m = date3.getMonth() + 1, // january is month 0 in javascript
d = date3.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
datestring = [y, pad(m), pad(d)].join("-");
console.log("DATESTRING", datestring);
divCode += '<div class="swiper-slide" id="_' + datestring + '" data-hash="' + datestring + '"><b>' +datestring+ '</b><br><br>' +tableCode+ '</div>';
// Incrementing date by 1
date3 = date3.setDate(date3.getDate() + 1);
}
The setDate method works inplace on the object, and the return value of the function is the timestamp of the new date.
When you did:
date3 = date3.setDate(date3.getDate() + 1);
in your function, the date3 is now an integer (and not a Date() object), so basically what your code does now is 1502742691133.getFullYear(), and this is wrong.
You don't need to set the value of setDate() to date3. Just do:
date3.setDate(date3.getDate() + 1);

Why do I get an NaN for my first date parse?

I am trying to convert two strings to dates but I am getting an NaN for an obviously date string.
Can anyone tell me why this happens?
Code:
function SortMaster() {
return function (a, b) {
var aValue = a, bValue = b, aLength = a.length, bLength = b.length;
var aType = Object.prototype.toString.call(aValue);
var bType = Object.prototype.toString.call(bValue);
var aasd = Date.parse(aValue);
var basd = Date.parse(bValue);
var aDate = (new Date(Date.parse(aValue))).toISOString().slice(0, 10).replace(/-/g, "");
var bDate = (new Date(Date.parse(bValue))).toISOString().slice(0, 10).replace(/-/g, "");
var highestValue = Math.max(aLength, bLength);
for (var i = 0; i < highestValue; i++) {
}
};
}
The value for a is a date string "21.10.2014 14:52:24"
The value for b is also a date string "04.04.2014 15:04:36"
The problem is that a is in dd.mm.yyyy format, seems like this is not recognizable as date by javascript which expected an mm.dd.yyyy format, so it threw an error because there's not such month as 21, but for b the error passed because the day was 04 which is less than 12 so it considered it as month while in fact it's day, so your format should not be dd.mm.yyyy
to demonstrate it check this jsFiddle
you see a2 is same date as a1 just in mm.dd.yyyy and it worked for a2 but a1 was invalid date
var a1 = '21.10.2014 14:52:24',
a2 = '10.21.2014 14:52:24',
b = '04.04.2014 15:04:36';
var dateA1 = new Date(Date.parse(a1)),
dateA2 = new Date(Date.parse(a2)),
dateB = new Date(Date.parse(b));
console.log('a1:' + dateA1); // error, Invalid Date
console.log('a2:' + dateA2);
console.log('b:' + dateB);
The issue was that the input string have had not the correct date format...
I have now created a function to create a correct format out of a date string.
function editDateString(dateString){
var dateStringSplits = dateString.split(' ');
var firstPart = dateStringSplits[0];
var secondPart = dateStringSplits[1];
var Year = firstPart.split(".")[2];
var Month = firstPart.split(".")[1];
var Day = firstPart.split(".")[0];
var Hour = secondPart.split(":")[0];
var Minute = secondPart.split(":")[1];
var Second = secondPart.split(":")[2];
return newDateString = Year + "-" + Month + "-" + Day + " " + Hour + ":" + Minute + ":" + Second;
}
Thanks to Mi-Creativity for his help!!!

Convert input type text into date format

I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.

Save excel file with current date and time through javascript

I want to open the excel file and then save the excel file and the name will be file name + current date and time. I am not getting this result for date I have used Date()
var wshell;
var excel = new ActiveXObject("Excel.Application");
alert(excel);
var excel_file = excel.Workbooks.Open("book2.xlsx");
excel.Visible = true;
var objWorkbook = excel.Workbooks.Add();
var objWorksheet = objWorkbook.Worksheets(1);
objWorkbook.Worksheets(1).Activate;
objWorksheet.name = "test";
objWorksheet.Paste;
objWorksheet.columns.autofit;
window.clipboardData.setData("Text","");
var today = new Date();
document.write(today.toString());
excel_file.SaveAs("d:\\board.xls"+ (today.toString()));
alert("data saved");
today contains an illegal character (:) to use in a file name. You need to clean your date, for example something like this:
var today = new Date().toString().replace(/[^\w]/g, '');
And when saving, the timestamp should be a part of the file name instead of the extension:
excel_file.SaveAs("D:\\board" + today + ".xls");
Instead of .toString().replace() you can format the timestamp to look like you want with methods of Date object.
EDIT
Here's the code with which you can modify your dates. I've simplified getDate() for you, hence you can modify it to return a date in what ever form you want.
var today = new Date(),
time = today.toTimeString().split(':').join('').substr(0, 4),
timestamp = getDate('dd_mm_yyyy', today) + '_' + time;
function getDate (mode, userdate) {
var dte = userdate || new Date(),
d = dte.getDate().toString(),
m = (dte.getMonth() + 1).toString(),
yyyy = dte.getFullYear().toString(),
dd = (d.length < 2) ? '0' + d : d,
mm = (m.length < 2) ? '0' + m : m,
yy = yyyy.substring(2, 4);
switch (mode) {
case 'dd_mm_yyyy': return dd + '_' + mm + '_' + yyyy;
case 'yyyymmdd': return yyyy + mm + dd;
default: return dte;
}
}
timestamp contains a date in wanted form after run the code above.

Check if one date is between two dates

I need to check if a date - a string in dd/mm/yyyy format -
falls between two other dates having the same format dd/mm/yyyy
I tried this, but it doesn't work:
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
alert("date contained");
I used debugger and checked, the to and from variables have isNaN value.
Could you help me?
Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
console.log(check > from && check < to)
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Here is a Date Prototype method written in typescript:
Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
return !minDate ? true : this.getTime() >= minDate.getTime()
&& !maxDate ? true : this.getTime() <= maxDate.getTime();
};
I did the same thing that #Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];
dates.forEach(element => {
let parts = element.split("/");
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
if (date >= from && date < to) {
console.log('dates in range', date);
}
})
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle:
https://jsfiddle.net/zm75cq2a/
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This may feel a bit more intuitive. The parameter is just a valid date string.
This function returns true if the date passed as argument is in the current week, or false if not.
function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()
// create a date instance with the function parameter
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)
// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date by substracting the day index (number) in the week from the day value (count)
//in the month (like october 15th - 5 (-> saturday index)) and +1 because
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Fiddle
This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.
const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';
if (
DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
console.log('within range');
} else {
console.log('not in range');
}

Categories

Resources