0

i have this piece of code:

<script  type="text/javascript">
function CompareDates(id)
{
var months = new Array(12);
 months[1]=  "Jan";
 months[2] = "Feb";
 months[3] = "Mar";
 months[4] = "Apr";
 months[5] = "May";
 months[6] = "Jun";
 months[7] = "Jul";
 months[8]=  "Aug";
 months[9] = "Sep";
 months[10] = "Oct";
 months[11] = "Nov";
 months[12] = "Dec";


var d = new Date(id);

var retVal =d.getDate()+' '+ months[d.getDate()]+' '+d.getFullYear()
return retVal; } 

</script>

and calendar tag:

<p:calendar 
id="testDate" 
styleClass="calendar"
pattern="d MMM yyyy"
maxlength="10"
onfocus="$(this).mask('99/99/9999');"
onchange="$(this).val(CompareDates($(this).val()))"
>
<p:watermark for="testDate" value="dd/mmm/yyyy" />
</p:calendar>

and i need to add an if/else statement in it so that if date is >31 and months is >12, the date will return 'false' as for now,

it returns 'NaN undefined NaN'

Can someone tell me where and how should i add the condition in?

I did this:

var d = new Date(id);

if (d.getDate > '31' || months > '12'){
return false;

} else {
var retVal =d.getDate()+' '+ months[d.getDate()]+' '+d.getFullYear()
return retVal; } 
}

and result is, even if the date is within the limit it'll still return false.

Carinenxe
  • 17
  • 1
  • 8

5 Answers5

1

Here this will work:

function compareDate(dateValue){
    if(arguments.length){
        date = dateValue.split("/") //when date is entered in DD/MM/YYYY format. We split days months and year
        days = date[0] //get DD
        month = date[1] //get MM
        year = date[2] //get YYYY
        d = new Date();
        total_days = new Date(d.getYear(),d.getMonth()+1,0).getDate()
        if(days > 0 && days <= total_days && month >0 && month <= 12){
            //your success message
        }else{
            //your error message like date not valid
        }
    }else{
        //no date specified
    }
}
Zeeshan Hyder
  • 520
  • 5
  • 14
  • Hi zee, i am trying to convert user's input of month-number to month-name therefore i made my month index to start from 1. – Carinenxe May 20 '14 at 03:12
  • I mistook || to be (and), instead of (or), as pointed out by someone earlier. – Carinenxe May 20 '14 at 03:13
  • yeah but getMonth() function returns months index from zero only. You can check. Jan is returned as 0. – Zeeshan Hyder May 20 '14 at 03:13
  • do you mean it should be months[d.getMonth()] instead? – Carinenxe May 20 '14 at 03:23
  • i need 'Jan' to be returned, instead of 0 though, i changed it to 'getMonth' and my array to start from 0, and when i entered '01', 'Dec' is returned. – Carinenxe May 20 '14 at 03:24
  • 1
    Yes. You are correct. months[d.getMonth()] will do it. Will return Jan, instead of 0. I dont understand why do you need to use, because you are getting both month and date from javascript functions. They wont be wrong. So your if will always be false. – Zeeshan Hyder May 20 '14 at 03:41
  • hi.. i don't exactly understand what you mean by i am getting both month and date from javascript....? – Carinenxe May 20 '14 at 06:24
  • When you use if(d.getDate() >31 && month> 12 ) d.getDate() > 31 will always be false because no month is of 32 days. Also you are using second condition month > 12, it is unclear where month's value is coming from. You are trying to check month array against 12 which is wrong. – Zeeshan Hyder May 20 '14 at 07:13
  • if that's the case how should i set a condition which will return false if the user keys in any invalid dates? instead of system returning 'NaN' – Carinenxe May 20 '14 at 07:25
  • var total_month = new Date(d.getYear(),d.getMonth()+1,0).getDate(). if(user_provided_month > total_month && user_provided_month > months.length ) { //throw error } else { //ok } – Zeeshan Hyder May 20 '14 at 07:38
  • Here, the above code checks if the user provided wrong days in month or wrong no of months – Zeeshan Hyder May 20 '14 at 07:40
  • so my 'user_provided_month' will be 'months' am i right? according to my codes? – Carinenxe May 20 '14 at 07:56
  • i do not understand this part: **d.getYear(),d.getMonth()+1,0).getDate().** could you kindly explain the logic of this sentence for me? thank you very much! – Carinenxe May 20 '14 at 07:58
  • and everytime i use '&&', i get this error: **The entity name must immediately follow the '&' in the entity reference** – Carinenxe May 20 '14 at 08:02
  • yes.... d.getYear(),d.getMonth()+1,0).getDate().It gets the total number of days for current month. I need to see the code once before i can actually help. Would you mind? – Zeeshan Hyder May 20 '14 at 08:31
  • alright done, this two pieces of code are all i have. – Carinenxe May 20 '14 at 09:52
0

Do it with case:

switch (d) {
case 29:
    alert (29 days);
    break;
case 30:
    alert (30 days);
    break;
case 31:
    alert (31 days);
    break;
}
a coder
  • 546
  • 4
  • 23
0

You created a Date object d from id parameter. In this way, it is impossible that Date d to be outside the date and month range... so probably your checking is not necessary.

Just in case you still need an answer, I would say:

if (d.getDate > '31' || months > '12'){
return false;
} else { //...

Note that months is an array. Probably you meant d.getMonth() rather than months. d.getDate need to be d.getDate().

Additional note: getMonth() method returns 0-11, i.e. 0 for January and 11 for December. You will probably need to adjust for the checking.

Kenneth L
  • 260
  • 2
  • 14
  • hi! i need the array to start from [1] because i am supposed to convert user's input of month number to month name. – Carinenxe May 20 '14 at 03:11
  • Simple way - make the array start from [0] i.e. `Months[0]="Jan"; Months[1]="Feb"` etc. This doesn't look good at the beginning, but you will appreciate it as programmers prefer array to start from 0. A not-so-good-looking way: report `Months[d.getMonth()+1]`. – Kenneth L May 20 '14 at 03:17
  • You can further simply your code for the Array declaration part as `var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];` rather than those 13 lines from `var months = new Array(12);` to `months[12] = "Dec";`. – Kenneth L May 20 '14 at 03:21
0

You just need to make couple of changes to your code:

  1. Change array values starting from index 0 and so on. months[0]= "Jan"; instead of months[1]= "Jan";
  2. Date object already has getMonth() method use it to publish month

    var retVal =d.getDate()+' '+ months[d.getMonth()]+' '+d.getFullYear();

    1. No additional condition required.

Suggestions::

  1. you can use shorthand method to compress your code var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec");
  2. I dont grasp why you have used (id)...I believe it is not required. But let me know if missed anything. Will be glad to answer.

Here is the complete code:

<script  type="text/javascript">
CompareDates();
function CompareDates()
{
var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var d = new Date();
var retVal =d.getDate()+' '+ months[d.getMonth()]+' '+d.getFullYear();
alert(retVal);
return retVal; 
} 

</script>
  • Hi! this piece of code was provided by another user from here and he included the (id) therefore i did not make any changes to it, though it did help me achieve what i initially needed. I have made the changes accordingly but now, no matter what i manually type for the month, it'll still return the current month :( would you like to see the complete piece of code for better reference? – Carinenxe May 20 '14 at 03:38
0

It's not clear what you are asking.

> function CompareDates(id) {

What is id? Is it a string or a time value? Function names starting with a capital letter are, by convention, reserved for constructors, so better to use:

function compareDates() {

Also, this doesn't seem to compare dates, is the name still appropriate? Or maybe it's a work in progress. :-)

> var months = new Array(12);
> months[1]= "Jan";
  ...
> months[12] = "Dec";

Consider using an array literal. It seems you are trying to convert a Date object month number to the English month abbreviation. In that case, make the array zero indexed (as others have suggested):

var months = ['Jan','Feb','Mar','Apr','May','Jun',
              'Jul','Aug','Sep','Oct','Nov','Dec'];

> var d = new Date(id);

Hopefully id is a time value since letting the Date constructor parse strings is problematic and inconsistent in browsers. I'll assume that it's creating a suitable Date object.

> var retVal =d.getDate() + ' ' + months[d.getDate()] + ' ' + d.getFullYear()

To get the appropriate month name:

var retVal = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();

however it's not common to use a space as a separator, "-" and "/" are more common.

As has also been said, once id is converted to a Date, it will always fit the parameters for a valid date. If it can't be converted to a valid date, it will evaluate to NaN.

However, if id is a string (and it should not be, see above) like "23/5/2014" then you can vlidate it using the answers to How to validate a date.

Edit

So it seems id is a string. You can't specify a format for Date.parse, it may accept particular strings but it's generally unreliable so manually parse the string. Assuming it's in d/m/y format:

// Expects d/m/y
function parseDMY(s) {
  var b = s.split(/\D/);
  return new Date(b[2], --b[1], b[0]);
}

The date can be validated using:

// Expects d/m/y
function isValidDate(s) {
  var b = s.split(/\D/);
  var d = parseDMY(s);
  return !!d && d.getFullYear() == b[2] && d.getDate() == b[0];
}

console.log(isValidDate('29/2/2014')); // false
console.log(isValidDate('29/2/2016')); // true

The above will return either true or false depending on whether it is passed a valid date in d/m/y format. For some browsers, the above will fail if the year is from 1 to 99 as they assume such dates are 20th century and make them 1901 to 1999.

If you wish to also handle dates in the first century, use:

// Expects d/m/y
function parseDMY(s) {
  var b = s.split(/\D/);
  var d = new Date();
  d.setHours(0,0,0,0);
  d.setFullYear(b[2], --b[1], b[0]);
  return d;
}
Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Hi!! thanks SO much for your detailed explanation of my array, i'm really new at coding but for my internship, i was asked to do it. and that code was provided by one of you experts here :) now i understand it better and the problem for me now is that my supervisor does not wish to see 'NaN' when it can't be converted. – Carinenxe May 20 '14 at 06:05
  • How can i change that to something else? and also, i have tried to make the array zero indexed but it does not seem to work for me. – Carinenxe May 20 '14 at 06:05
  • it will only return months 'nov' and 'dec' – Carinenxe May 20 '14 at 06:10
  • sorry my mistake, it does work. however the format that it converts from is mm/dd/yyyy, so if i input '01/03/2013' it'll return '3 Jan 2013' even though i have specified the pattern to be d MMM yyyy. and it only happened after i changed months[d.getDate] to months[d.getDate]. could you kindly explain to me why is this the case? your help is greatly appreciated! – Carinenxe May 20 '14 at 06:20