I have date string like this 1 May 2010 To 15 Aug 2016 .I just want to check this as date string on my function and not to proceed on a function.When I'm checking this string with new Date(value) its returning Invalid date.How can I check this as date?
I would use js date library moment js for this.
var checkDate = function (str){
var dates = str.split("To");
var flag = true;
for(var i = 0; i < dates.length; i++) {
if (moment(dates[i]).isValid()) {
flag = false;
}
}
return flag;
}
I have created a fiddle for that
https://jsfiddle.net/Refatrafi/wj5zc75e/
var str = "1 May 2010 To 15 Aug 2016";
//First split string
var array = str.split("To");
//then check if both are dates
for(var i = 0; i < array.length; i++) {
if(isNaN(new Date(array[i]))) { //Checking date
alert(array[i]+ ' is not valid date');
}
}
When parsing strings you should always provide the format of the string to parse. This can be done very simply using the ES5 every method:
var isValid = '1 May 2010 To 15 Aug 2016'.split(' To ').every(function(s) {
return moment(s,'D MMM YYYY').isValid();
});
console.log(isValid);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
If arrow functions are OK, then:
var isValid = '1 May 2010 To 15 Aug 2016'.split(' To ').every(s=>moment(s,'D MMM YYYY').isValid());
does the job.
var checkDate = function (str){
var dates = str.split("To");
for(var i = 0; i < dates.length; i++) {
if (moment(dates[i]).isValid()) {
return true;
} else {
return false;
}
}
}
I can use this function in my code anywhere.
Related
I am trying to write a function that returns a TRUE or FALSE value based on whether the date is present in the array or not. Currently I have this:
function isInArray(value, array) {
var a = array.indexOf(value) > -1;
if (a == false) {
return false; //DATE DOES NOT EXIST
}
else {
return true; //DATE EXISTS IN ARRAY
}
}
Now normally I would use a for loop, however I am generating a list of dates between a start date and end date with this while loop:
while (day > 0) {
var tDate = new Date(sDate.addDays(dayCounter));
datesArray.push(tDate);
day = day - 1; //DEDUCT THE DAYS AS ADDED
var dateExists = isInArray(value, array);
if (dateExists == false) {
}
else {
matchedDays++;
}
daysCounter++;
}
this however is not working and always returns FALSE, what do I need to do to make this work and return the correct value?
sample data: ARRAY[26/12/2016, 27/12/2016, 28/12/2016, 29/12/2016]
value passed in [27/12/2016]
return TRUE if the value exists in the array
return FALSE if the value does not exist in the array
probably a simple mistake above! so thankyou for any help on this. also will a time affect the date when its being checked?
You can try using the find() method (if ecmascript is supported):
Case: array contains strings
var array = ["26/12/2016", "27/12/2016", "28/12/2016", "29/12/2016"];
var value1 = "26/12/2016"; //exists
var value2 = "26/12/2026"; //doesn't exist
function isInArray(array, value) {
return (array.find(item => {return item == value}) || []).length > 0;
}
console.log(isInArray(array, value1));
console.log(isInArray(array, value2));
Case: array contains Date objects
var array = [new Date("December 26, 2016 00:00:00"), new Date("December 27, 2016 00:00:00"), new Date("December 28, 2016 00:00:00"), new Date("December 29, 2016 00:00:00")];
var value1 = new Date("December 26, 2016 00:00:00"); //exists
var value2 = new Date("December 16, 2026 00:00:00"); //doesn't exist
function isInArray(array, value) {
return !!array.find(item => {return item.getTime() == value.getTime()});
}
console.log(isInArray(array, value1));
console.log(isInArray(array, value2));
you can use includes function.
ri = ["26/12/2016", "27/12/2016", "28/12/2016", "29/12/2016"];
ri.includes("20/12/2016"); //False
ri.includes("26/12/2016"); //True
Alternative to IE
indexOf return the position of value.
var pos = ri.indexOf("26/12/2016"); // 0
var pos = ri.indexOf("20/12/2016"); // -1
var pos = ri.indexOf("27/12/2016"); // 1
if(pos > -1){ //is in array }
Something like
function isInArray(value, array) {
for (var i = 0; i < array.length; i++) {
if (value == array[i]) {
return true;
}
}
return false;
}
should work..
You may have to use different comparing operations though.
I solved by getting only the first 15 characters in the dates, this is my snippet:
//get the first 15 characters of each date in my array (hdates)
for (i=0;i<hdates.length;i++){
hdates[i]=hdates[i].toString().substring(0,15); //converts dates to 15 characters long strings
}
function highlight(date) {
if(hdates.indexOf(date.toString().substring(0,15))>-1) { //converts my date element to compare, too
return'ok';
} else {
return 'ko';
}
}
if you don't want to alter your array, I'd suggest you to clone it and then convert the dates in 15 character long strings
I have my dates converted to moment.js, and now I want to compare it with another date ('now' in this case).
Just a plain compare with a date object seems to be a lot faster than using moment.js isAfter function.
Will this simple compare work in all locales?
Am I missing something here?
Is there a very specific reason why isAfter seems to create a new moment object instead of taking a shortcut when it's a Date object?
All my dates are in UTC.
function executeTests() {
isAfterTest();
compareTest();
}
function isAfterTest() {
console.time('isAfterTest');
var now = new Date();
var dateOfBirth = moment('2000-01-01');
for (var i = 0; i < 50000; i++) {
var x = dateOfBirth.isAfter(now);
}
console.timeEnd('isAfterTest');
}
function compareTest() {
console.time('compareTest');
var now = new Date();
var dateOfBirth = moment('2000-01-01');
for (var i = 0; i < 50000; i++) {
var x = dateOfBirth > now;
}
console.timeEnd('compareTest');
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment-with-langs.js"></script>
<button onclick="executeTests();">Run Test</button>
Results:
isAfterTest: 3754.000ms (index):32
compareTest: 24.000ms
See: http://jsfiddle.net/t4grs0p7/2/
Looking at the documentation http://momentjs.com/docs/ the isAfter method accepts different types of Date format:
moment().isAfter(Moment|String|Number|Date|Array);
This means it needs to do type checking and then convert it to a date object before running the calculation.
One way you could reduce this impact would be to pass in a Moment object as the comparison date:
function isAfterTest() {
console.time('isAfterTest');
var now = moment();
var dateOfBirth = moment('2000-01-01');
for (var i = 0; i < 50000; i++) {
var x = dateOfBirth.isAfter(now);
}
console.timeEnd('isAfterTest');
}
I created a fiddle to compare, but that doesn't seem to improve it much at all:
http://jsfiddle.net/kmturley/t4grs0p7/7/
Looking at your version I believe you should be using valueOf() method to compare the values:
window.compareTest2 = function() {
console.time('compareTest2');
var now = moment().valueOf();
var dateOfBirth = moment('2000-01-01').valueOf();
for ( var i = 0; i < 50000; i++ )
var x = dateOfBirth > now;
console.timeEnd('compareTest2');
}
Here is a working example:
http://jsfiddle.net/kmturley/t4grs0p7/8/
I've got a startdate and enddate from inputs. And I need to put all the dates from the startdate until the enddate into the database. Therefore I need to make a loop like this:
FOR i = startdate; i <= enddate; i + 1 day
{
here i use the date
}
How do I make such a loop with dates from input boxes?
I get 'invalid date' if I try to do this:
var endDate = new Date($("#enddate").val());
And I can't use the endDate.getTime() like I need as you said in the answer, if I do it like this.
var endDate = $("#enddate").val());
var endDateTime = endDate.getTime();
So basically: How can I convert the input to a date? The input of enddate is like this: dd/mm/yyyy.
No it's not an SQL question, I need to do this is javascript because I need to check the dates first.
Thank you for helping me out ;)
Would a loop like this work?:
var current_date = new Date("01/13/2013");
var end_date = new Date("01/20/2013");
var end_date_time = end_date.getTime();
while (current_date.getTime() < end_date_time) {
console.log(current_date);
current_date.setDate(current_date.getDate()+1);
}
http://jsfiddle.net/Sn6Ws/
Depending on the format of your textboxes' values, you can set it up like this:
$(document).ready(function () {
$("#btn").on("click", function () {
dateLooper(function (cur, end) {
console.log("Current date: " + cur.toString() + ", End Date: " + end.toString());
});
});
});
function dateLooper(callback) {
var start_date_text = document.getElementById("start_date").value;
var end_date_text = document.getElementById("end_date").value;
var current_date = new Date(start_date_text);
var end_date = new Date(end_date_text);
var end_date_time = end_date.getTime();
while (current_date.getTime() < end_date_time) {
//console.log(current_date);
callback.call(this, current_date, end_date);
current_date.setDate(current_date.getDate()+1);
}
}
http://jsfiddle.net/Sn6Ws/1/
Per your comments that explain the date are in the format "dd/mm/yyyy", you could use something like this:
var start_date_text = document.getElementById("start_date").value;
var start_split = start_date_text.split("/");
if (start_split.length != 3) {
return false;
}
start_date_text = start_split[1] + "/" + start_split[0] + "/" + start_split[2];
var end_date_text = document.getElementById("end_date").value;
var end_split = end_date_text.split("/");
if (end_split.length != 3) {
return false;
}
end_date_text = end_split[1] + "/" + end_split[0] + "/" + end_split[2];
to get the dates in the right format before passing them to new Date. Here's an updated jsFiddle that demonstrates it:
http://jsfiddle.net/Sn6Ws/4/
Of course, be careful that if the dates don't come in with the specified format (in case users can type this in or something), the code will most likely throw an error. You can obviously put more checks in to make sure certain things set before proceeding with certain operations (like making sure each item is a number/integer, making sure the days are in the range 1 to 31, etc.). So for that reason, you may want to go the route of regular expressions. At least with regular expressions, you can specify a specific pattern and know whether it matches perfectly or not, and immediately get the values you need to build a date.
Using regular expressions, here's an example that isn't complete but should hopefully help:
function dateLooper(callback) {
var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var start_date_text = document.getElementById("start_date").value;
var start_match = re.exec(start_date_text);
if (start_match) {
var valid = true;
// Set `valid` variable based on the following
// Validate start_match[1] is valid day
// Validate start_match[2] is valid month
// Validate start_match[3] is valid year
if (valid) {
start_date_text = combineDate(start_match);
} else {
return false;
}
} else {
return false;
}
var end_date_text = document.getElementById("end_date").value;
var end_match = re.exec(end_date_text);
if (end_match) {
var valid = true;
// Set `valid` variable based on the following
// Validate end_match[1] is valid day
// Validate end_match[2] is valid month
// Validate end_match[3] is valid year
if (valid) {
end_date_text = combineDate(end_match);
} else {
return false;
}
} else {
return false;
}
var current_date = new Date(start_date_text);
var end_date = new Date(end_date_text);
var end_date_time = end_date.getTime();
var days_spent = 0;
while (current_date.getTime() < end_date_time) {
days_spent++;
callback.call(this, current_date, end_date, days_spent);
current_date.setDate(current_date.getDate()+1);
}
return days_spent;
}
function combineDate(re_match) {
return re_match[2] + "/" + re_match[1] + "/" + re_match[3];
}
http://jsfiddle.net/Sn6Ws/6/
I am having a datatable return a number of Dates received - they are coming back in the format below(will always take this format):
/Date(1362045881257)/
how can I easily strip this to just the epoch digits so I can then convert into a readable date.
I have tried the following so far but it is not working as expected. So the first thing I was trying to remove was just the ( ) - then I was going to do another .replace to remove the / / and then remove the Date which would leave me with just the digits.
success: function (msg) {
for (var i = 0; i < msg.aaData.length; i++) {
var date = msg.aaData[i].DateReceived;
date.replace(/\(|\)/g, '');
alert(date);
}
fnCallback(msg);
},
success: function (msg) {
for (var i = 0; i < msg.aaData.length; i++) {
// toString() below might be redundant!
var date = msg.aaData[i].DateReceived.toString();
var reg = /[^0-9]/g;
var epoch = date.replace(reg, ''));
alert(epoch);
}
fnCallback(msg);
},
Can anyone help me in finding the solution
i just want to compare two dates in dd/mm/yyyy format.
function compareDate(dt1 , dt2 , formatString){var returnVal = 2;
var dt1Parts;
var dt2Parts;
var dt1dd;
var dt1mm;
var dt1yyyy;
var dt2dd;
var dt2mm;
var dt2yyyy;
if(formatString == 'dd/mm/yyyy'){
dt1Parts = dt1.split('/');
dt2Parts = dt2.split('/');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}
else if(formatString == 'dd-mm-yyyy'){
dt1Parts = dt1.split('-');
dt2Parts = dt2.split('-');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}else{
alert(formatString+' format is not supported.');
}
if(dt1yyyy == dt2yyyy && dt1mm == dt2mm && dt1dd == dt2dd){
returnVal = 0;
}
else if(dt1yyyy > dt2yyyy){
returnVal = 1 ;
}else if(dt1yyyy == dt2yyyy ){
if(dt1mm > dt2mm){
returnVal = 1;
}else if(dt1mm == dt2mm){
if(dt1dd > dt2dd){
returnVal = 1;
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
return returnVal;
}
Thanks in advance,
Shilpa
Invert the strings to yyyy/mm/dd, or convert them to a number or Date object.
The simplest way just for comparison would be ASCII order. Invert using something like this:
function invert(date) {
return date.split(/[/-]/).reverse().join("")
}
function compareDates(date1, date2) {
return invert(date1).localeCompare(invert(date2));
}
Here's how you convert that string format to a date:
var myString = "17/07/1979",
correctFormat = myString.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$2/$1"),
myDate = new Date(correctFormat);
Without knowing what language or class libs you're working with:
Method 1: Resort your strings to be yyyymmdd and the do string compare.
Method 2: Stuff yyyy mm and dd into the high, middle, and low bits of an integer and compare.
The easiest way is probably to create 2 javascript Date objects from your input string. You could achieve that by chopping your input into day, month and year. You can use the 'substring' function for that.
Then you can do:
var firstDate = new Date(year1, month1, day1);
var secondDate = new Date(year2, month2, day2);
Once you have 2 date objects, you can use the normal compare operators:
if (firstDate > secondDate)
// do something
else
...
Try this
var date1=new Date('your date1 string');
var date2=new Date('your date2 string');
var difference=new Date(date1.getTime()-date2.getTime());
if ($.datepicker.parseDate('dd/mm/yy', fDate) > $.datepicker.parseDate('dd/mm/yy', tDate)) {
//do something
}
You can compare two dates.Here I compare from date greater than to date
try this