Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q16 How can I compare a date in a string with todays date?

You are here: irt.org | FAQ | JavaScript | Date | Q16 [ previous next ]

<script language="JavaScript"><!--
function isitToday(dateString,dateType) {
/*
   function isitToday
   parameters: dateString dateType
   returns: boolean

   dateString is a date passed as a string in the following
   formats:

   type 1 : 19970529
   type 2 : 970529
   type 3 : 29/05/1997
   type 4 : 29/05/97

   dateType is a numeric integer from 1 to 4, representing
   the type of dateString passed, as defined above.

   Returns true if the date passed is equal to todays date
   Returns false if the date passed is NOT equal to todays
   date or if dateType is not 1 to 4.
*/


    var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());

    if (dateType == 1)
        var date = new Date(dateString.substring(0,4),
                            dateString.substring(4,6)-1,
                            dateString.substring(6,8));
    else if (dateType == 2)
        var date = new Date(dateString.substring(0,2),
                            dateString.substring(2,4)-1,
                            dateString.substring(4,6));
    else if (dateType == 3)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(3,5)-1,
                            dateString.substring(0,2));
    else if (dateType == 4)
        var date = new Date(dateString.substring(6,8),
                            dateString.substring(3,5)-1,
                            dateString.substring(0,2));
    else
        return false;

    if (date.toString() == today.toString())
        return true;
    else
        return false;
}

if (isitToday("19970529",1)) alert('true'); else alert('false');

if (isitToday("970529",2)) alert('true'); else alert('false');

if (isitToday("29/05/1997",3)) alert('true'); else alert('false');

if (isitToday("02/06/97",4)) alert('true'); else alert('false');
//--></script>

Feedback on 'Q16 How can I compare a date in a string with todays date?'

©2018 Martin Webb