簡體   English   中英

如何驗證 yyyy-mm-dd hh:mm:ss 格式

[英]How do I validate yyyy-mm-dd hh:mm:ss format

我看到這個用於驗證mm/dd/yyyy or mm-dd-yyyy小提琴,但我想驗證yyyy-mm-dd hh:mm:ss格式,我如何確保今天小於使用 yyyy 的日期yyyy-mm-dd hh:mm:ss格式?。

這就是我啟動日期時間選擇器的方式..

$("#startDate, #endDate").datetimepicker({ dateFormat: 'yyyy-mm-dd hh:mm:ss'}); 

請幫我完成這件事。

謝謝

檢查yyyy-mm-dd hh:mm:ss字符串相互之間非常簡單,因為它們已經有序了; 你可以忘記這些數字的基礎,並簡單地按字符串比較執行<> 這可能不適用於其他日期。

function compISOZDate(d1, d2) { // d1 is
    if (d1  <  d2) return -1;   //    smaller
    if (d1 === d2) return  0;   //    the same
    /*   else   */ return  1;   //    bigger
}

驗證日期有點復雜,因為月份的天數可能會發生變化。 你可以忽略這個事實,只測試數字,但我更喜歡會議的一半,引入上限。

function verifyMyDate(d) {
    var re = /^\d{4}-(0[1-9]|1[0-2])-([0-2]\d|3[01]) (0\d|1[01]):[0-5]\d:[0-5]\d$/;
    //         yyyy -       MM      -       dd           hh     :   mm  :   ss
    return re.test(d);
}

所以例如使用它

var d1 = '2013-10-07 11:58:26',
    d2 = '2012-06-14 19:22:03';
// check
if (!verifyMyDate(d1)) throw new Error('Invalid date: ' + d1);
if (!verifyMyDate(d2)) throw new Error('Invalid date: ' + d2);
// compare
compISOZDate(d1, d2); //  1, d1 is bigger than d2
// also
compISOZDate(d2, d1); // -1
compISOZDate(d1, d1); //  0

現在剩下的就是從輸入中獲取值。

您指定的日期格式為ISO 8601 大多數現代瀏覽器都支持此字符串格式的Date 解析 所以你可以做這樣的事情。

使用Javascript

var iso8601 = "2013-02-01 10:00:00",
    userDate = new Date(iso8601),
    today = new Date(),
    dateTime,
    date,
    time,
    value;

// check is valid date
if (isNaN(userDate)) {
    alert("invalid userDate");
}

// check if userDate is before today
if (userDate.getDate() < today.getDate()) {
    alert("userDate is in past");
}

// check the string specifically matches "yyyy-mm-dd hh:mm:ss" and is valid
function isGregorianLeapYear(year) {
    return year % 400 === 0 || year % 100 !== 0 && year % 4 === 0;
}

function daysInGregorianMonth(year, month) {
    var days;

    if (month == 2) {
        days = 28;
        if (isGregorianLeapYear(year)) {
            days += 1;
        }
    } else {
        days = 31 - ((month - 1) % 7 % 2);
    }

    return days;
}

if (typeof iso8601 !== "string") {
    alert("not an iso8601 string");
} else {
    dateTime = iso8601.split(" ");
    if (dateTime.length !== 2) {
        alert("missing date or time element");
    } else {
        date = dateTime[0].split("-");
        if (date.length !== 3) {
            alert("incorrect number of date elements");
        } else {
            value = +date[0];
            if (date[0].length !== 4 || value < -9999 || value > 9999) {
                alert("year value is incorrect");
            }

            value = +date[1];
            if (date[1].length !== 2 || value < 1 || value > 12) {
                alert("month value is incorrect");
            }

            value = +date[2];
            if (date[2].length !== 2 || value < 1 || value > daysInGregorianMonth(+date[0], +date[1])) {
                alert("day value is incorrect");
            }
        }

        time = dateTime[1].split(":");
        if (time.length !== 3) {
            alert("incorrect number of time elements");
        } else {
            value = +time[0];
            if (time[0].length !== 2 || value < 0 || value > 23) {
                alert("hour value is incorrect");
            }

            value = +time[1];
            if (time[1].length !== 2 || value < 0 || value > 59) {
                alert("minute value is incorrect");
            }

            value = +time[2];
            if (time[2].length !== 2 || value < 0 || value > 59) {
                alert("second value is incorrect");
            }
        }
    }
}
console.log(userDate);
console.log(today);

的jsfiddle

將ValidateDate函數中的RegExp更改為以下代碼

function ValidateDate(dtValue)
{
   var dtRegex = new RegExp(/\b\d{4}[\/-]\d{1,2}[\/-]\b\d{1,2} (0\d|1[01]):[0-5]\d:[0-5]\d$\b/);
   return dtRegex.test(dtValue);
}

嘗試這個讓我知道,同樣的方式你也可以驗證hh:mm:ss

對於24小時變化,而不是AM / PM,使用:

regex = new RegExp(^\d{4}-(0[1-9]|1[0-2])-([0-2]\d|3[01]) (0\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$);

這是我寫的並且工作正常:

function validateDate(dtValue)   {
  // Format expected dd/mm/aaaa or dd-mm-aaaa (French Date)
  // Accept also d/m/aaaa or d-m-aaaa (ok for MySQL Database to have one number only for days and months)
  // Before the insert into database I will convert to aaaa-mm-jj or aaaa-m-j
  var dtRegex = new RegExp(/\b(0?[1-9]|([1-2]?[0-9]|3[0-1]))[\/-]([0]?[1-9]|1[0-2])[\/-]\b\d{4} ([0-1]?[0-9]|2[0-3]):[0-5]\d$\b/);
  // Accept range => (01 to 31)  (/ or -) (01 to 12) (/ or -) (4 numbers) space (00 to 23) : (00 to 59)

  var bValidateDate= dtRegex.test(dtValue);

  // Test if bValidateDate true, test and throw out (accepted from regex expression) : 
  // 30/02, 31/02, 31/04, 31/06, 31/09, 31/11
  // 30-02, 31-02, 31-04, 31-06, 31-09, 31-11

  // Get the 5 first characters
  var sFebruary29= dtValue.substring(0, 5);

  if (bValidateDate)
  {
    var aOfDateErrors= ["30/02", "31/02", "31/04", "31/06", "31/09", "31/11", "30-02", "31-02", "31-04", "31-06", "31-09", "31-11"];
    if (aOfDateErrors.indexOf(sFebruary29) > -1)
    {
      bValidateDate= false;
    }
  }

  // Then, if bValidateDate is still true (good format)
  // check if the date is a leap year to accept 29/02 or 29-02
  // And finally, my customer asked me to have a year between 2017 and now
  if (bValidateDate)
  {
    // Get the year
    var sYear= dtValue.substring(6, 10);
    // Customer's constraints
    var bYearCustomerOK= ((parseInt(sYear) >= 2017) && (parseInt(sYear) <= new Date().getFullYear()));
    // I promise, this is the "last test'em all !"
    var bFinalDate= (bYearCustomerOK) && (sYear % 400 === 0 || sYear % 100 !== 0 && sYear % 4 === 0) && ((sFebruary29 == "29/02") ||(sFebruary29 == "29-02"));
    if (! bFinalDate)
    {
      bValidateDate= false;
    }
  }

  return bValidateDate;
}

如果你發現一個糟糕的約會,請告訴我:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM