JavaScript validates the legality of a given date--an upgraded version

Source: Internet
Author: User
Tags date format requires return split version
javascript| Date

I used to send a "JavaScript validation of the legality of a given date", when the code could only validate dates and not validate time. A new upgraded version can validate a mixed string of date and time.

The code is as follows:

-----------------------

Verify that the given date is legitimate and that the parameter format requires: yyyy-mm-dd[HH:MI:SS] can correct the expression according to the situation
function IsDate (odatetime)
{
Validation of date formats requires a 2000-2,099 format of yyyy-mm-dd[Hh:mi:ss] and can be converted to the correct date correctly
var pat_hd=/^ (20\d{2}-(0[1-9]{1}) | ( 1[0-2]{1})-((0[1-9]{1}) | ( [1-2] {1} [0-9] {1}) | (3[0-1]{1})) {1} (\s\d{2}:\d{2}:\d{2})? $/;
try{
if (!pat_hd.test (odatetime)) throw "date illegal!" ";
var arr_dt=odatetime.split ("");
if (arr_dt[0]== ') throw ' date is illegal! ";
var odate=arr_dt[0];
var arr_hd=odate.split ("-");
var datetmp;
datetmp= New Date (Arr_hd[0],parsefloat (arr_hd[1)) -1,parsefloat (arr_hd[2));
if (Datetmp.getfullyear ()!=parsefloat (arr_hd[0)) | | Datetmp.getmonth ()!=parsefloat (arr_hd[1])-1 | | dateTmp.getDate ( )!=parsefloat (arr_hd[2]) throw "date illegal! ";
if (arr_dt[1] && arr_dt[1]!= ')
{
var otime=arr_dt[1];
var arr_ht=otime.split (":");
Datetmp.sethours (arr_ht[0],arr_ht[1],arr_ht[2]);
if (Datetmp.gethours ()!=parsefloat (arr_ht[0)) | | datetmp.getminutes ()!=parsefloat (arr_ht[1)) | | Datetmp.getseconds ( )!=parsefloat (arr_ht[2]) throw "date illegal! ";
}
}
catch (ex)
{
if (ex.description)
{return false;}
Else
{return false;}
}
return true;
}

Call:

------------------

Alert (IsDate ("2004-12-12 23:34:23"));

Alert (IsDate ("2004-12-12"));



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.