Nice programing

날짜를 확인하는 방법은 무엇입니까?

nicepro 2020. 11. 10. 22:17
반응형

날짜를 확인하는 방법은 무엇입니까?


누군가가 입력하면 2/30/2011잘못된 것이어야한다는 의미에서 날짜가 유효한지 테스트하려고합니다 .

날짜에 관계없이 어떻게 할 수 있습니까?


날짜 문자열의 유효성을 검사하는 간단한 방법 중 하나는 날짜 개체로 변환하고 테스트하는 것입니다.

// Expect input as d/m/y
function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d && (d.getMonth() + 1) == bits[1];
}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
  console.log(s + ' : ' + isValidDate(s))
})

이 방법으로 날짜를 테스트 할 때 날짜가 범위를 벗어나면 월이 변경되므로 월만 테스트하면됩니다. 월이 범위를 벗어난 경우에도 동일합니다. 모든 연도가 유효합니다.

날짜 문자열의 비트를 테스트 할 수도 있습니다.

function isValidDate2(s) {
  var bits = s.split('/');
  var y = bits[2],
    m = bits[1],
    d = bits[0];
  // Assume not leap year by default (note zero index for Jan)
  var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  // If evenly divisible by 4 and not evenly divisible by 100,
  // or is evenly divisible by 400, then a leap year
  if ((!(y % 4) && y % 100) || !(y % 400)) {
    daysInMonth[1] = 29;
  }
  return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
  console.log(s + ' : ' + isValidDate2(s))
})


RobG에서 제안한 첫 번째 함수 isValidDate (s)가 입력 문자열 '1 / 2 /'에 대해 작동합니까? 나는 YEAR가 검증되지 않았기 때문에 그렇지 않다고 생각합니다. (

내 제안은이 기능의 개선 된 버전을 사용하는 것입니다.

//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
        var bits = input.split('-');
        var d = new Date(bits[0], bits[1] - 1, bits[2]);
        return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}

moment.js를 사용하는 것이 좋습니다. 날짜를 순간적으로 제공하는 것만으로 유효성을 검사하고 dateFormat을 전달할 필요가 없습니다.

var date = moment("2016-10-19");

그런 다음 date.isValid()원하는 결과 제공합니다.

여기에 게시


이 솔루션은 날짜 부분이 정수인지 확인하거나 날짜 부분이 0보다 크고 32보다 작은 날짜와 같은 명백한 유효성 검사를 준수하는지 확인하는 것과 같은 명확한 날짜 유효성 검사를 처리하지 않습니다.이 솔루션은 이미 세 개의 날짜 부분이 모두 있다고 가정합니다 ( 년, 월, 일) 그리고 각각 이미 확실한 검증을 통과했습니다. 이러한 가정을 감안할 때이 방법은 단순히 날짜가 있는지 확인하는 데 효과적입니다.

예를 들어 2009 년 2 월 29 일은 실제 날짜가 아니라 2008 년 2 월 29 일입니다. 2009 년 2 월 29 일과 같은 새 Date 객체를 만들 때 어떤 일이 발생하는지 살펴보십시오 (JavaScript에서 월은 0에서 시작 함).

console.log(new Date(2009, 1, 29));

위 라인 출력 : Sun Mar 01 2009 00:00:00 GMT-0800 (PST)

날짜가 단순히 다음 달의 1 일로 롤링되는 방법에 주목하십시오. 다른 명백한 유효성 검사가 있다고 가정하면이 정보를 사용하여 다음 함수를 사용하여 날짜가 실제인지 확인할 수 있습니다 (이 함수는보다 편리한 입력을 위해 0이 아닌 월을 허용합니다).

var isActualDate = function (month, day, year) {
    var tempDate = new Date(year, --month, day);
    return month === tempDate.getMonth();
};

이것은 완전한 솔루션이 아니며 i18n을 고려하지 않지만 더 강력하게 만들 수 있습니다.


var isDate_ = function(input) {
        var status = false;
        if (!input || input.length <= 0) {
          status = false;
        } else {
          var result = new Date(input);
          if (result == 'Invalid Date') {
            status = false;
          } else {
            status = true;
          }
        }
        return status;
      }

이 함수는 주어진 입력이 유효한 날짜인지 여부에 대한 bool 값을 반환합니다. 전의:

if(isDate_(var_date)) {
  // statements if the date is valid
} else {
  // statements if not valid
}

방금 RobG 솔루션을 리메이크 합니다.

var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;

if (isLeap) {
  daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]

이것은 ES6 (let 선언 포함)입니다.

function checkExistingDate(year, month, day){ // year, month and day should be numbers
     // months are intended from 1 to 12
    let months31 = [1,3,5,7,8,10,12]; // months with 31 days
    let months30 = [4,6,9,11]; // months with 30 days
    let months28 = [2]; // the only month with 28 days (29 if year isLeap)

    let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);

    let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);

    return valid; // it returns true or false
}

이 경우에는 1 개월에서 12 개월을 계획했습니다. 0-11 기반 모델을 선호하거나 사용하는 경우 다음을 사용하여 배열을 변경할 수 있습니다.

let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];

날짜가 dd / mm / yyyy 형식 인 경우 일, 월 및 연도 함수 매개 변수를 제거하고이를 검색하려면 다음을 수행하십시오.

let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month  = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);

내 함수가 유효한 날짜이면 true를 반환하고 그렇지 않으면 false를 반환합니다 .D

function isDate  (day, month, year){
	if(day == 0 ){
		return false;
	}
	switch(month){
		case 1: case 3: case 5: case 7: case 8: case 10: case 12:
			if(day > 31)
				return false;
			return true;
		case 2:
			if (year % 4 == 0)
				if(day > 29){
					return false;
				}
				else{
					return true;
				}
			if(day > 28){
				return false;
			}
			return true;
		case 4: case 6: case 9: case 11:
			if(day > 30){
				return false;
			}
			return true;
		default:
			return false;
	}
}

console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));


요즘 자바 스크립트가 날짜 문자열의 유효성을 검사하는 간단한 방법이없는 것 같습니다. 이것은 최신 브라우저에서 "m / d / yyyy"형식으로 날짜를 구문 분석하는 가장 간단한 방법입니다 (이것이 ES5 이후 10이어야하므로 parseInt에 기수를 지정하지 않는 이유입니다).

const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
  if (!dateValidationRegex.test(strDate)) return false;
  const [m, d, y] = strDate.split('/').map(n => parseInt(n));
  return m === new Date(y, m - 1, d).getMonth() + 1;
}

['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
  console.log(d, isValidDate(d));
});


안녕하세요 아래 답변을 찾으십시오. 이것은 새로 생성 된 날짜를 확인하여 수행됩니다.

var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
        || d.getMonth() != (month - 1)
        || d.getDate() != date) {
    alert("invalid date");
    return false;
}

function isValidDate(year, month, day) {
        var d = new Date(year, month - 1, day, 0, 0, 0, 0);
        return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
    }

이것은 오래 전에 제기되었지만 여전히 가장 원하는 유효성 검사입니다. 기능이 거의 없는 흥미로운 블로그찾았습니다 .

/* Please use these function to check the reuslt only. do not check for otherewise. other than utiljs_isInvalidDate

Ex:-

utiljs_isFutureDate() retuns only true for future dates. false does not mean it is not future date. it may be an invalid date.

practice :

call utiljs_isInvalidDate first and then use the returned date for utiljs_isFutureDate()

var d = {};

if(!utiljs_isInvalidDate('32/02/2012', d))

if(utiljs_isFutureDate(d))

//date is a future date

else

// date is not a future date



 */

function utiljs_isInvalidDate(dateStr, returnDate) {

    /*dateStr | format should be dd/mm/yyyy, Ex:- 31/10/2017

     *returnDate will be in {date:js date object}.

     *Ex:- if you only need to check whether the date is invalid,

     * utiljs_isInvalidDate('03/03/2017')

     *Ex:- if need the date, if the date is valid,

     * var dt = {};

     * if(!utiljs_isInvalidDate('03/03/2017', dt)){

     *  //you can use dt.date

     * }

     */

    if (!dateStr)
        return true;
    if (!dateStr.substring || !dateStr.length || dateStr.length != 10)
        return true;
    var day = parseInt(dateStr.substring(0, 2), 10);
    var month = parseInt(dateStr.substring(3, 5), 10);
    var year = parseInt(dateStr.substring(6), 10);
    var fullString = dateStr.substring(0, 2) + dateStr.substring(3, 5) + dateStr.substring(6);
    if (null == fullString.match(/^\d+$/)) //to check for whether there are only numbers
        return true;
    var dt = new Date(month + "/" + day + "/" + year);
    if (dt == 'Invalid Date' || isNaN(dt)) { //if the date string is not valid, new Date will create this string instead
        return true;
    }
    if (dt.getFullYear() != year || dt.getMonth() + 1 != month || dt.getDate() != day) //to avoid 31/02/2018 like dates
        return true;
    if (returnDate)
        returnDate.date = dt;
    return false;
}

function utiljs_isFutureDate(dateStrOrObject, returnDate) {
    return utiljs_isFuturePast(dateStrOrObject, returnDate, true);
}

function utiljs_isPastDate(dateStrOrObject, returnDate) {
    return utiljs_isFuturePast(dateStrOrObject, returnDate, false);
}

function utiljs_isValidDateObjectOrDateString(dateStrOrObject, returnDate) { //this is an internal function
    var dt = {};
    if (!dateStrOrObject)
        return false;
    if (typeof dateStrOrObject.getMonth === 'function')
        dt.date = new Date(dateStrOrObject); //to avoid modifying original date
    else if (utiljs_isInvalidDate(dateStrOrObject, dt))
        return false;
    if (returnDate)
        returnDate.date = dt.date;
    return true;

}

function utiljs_isFuturePast(dateStrOrObject, returnDate, isFuture) { //this is an internal function, please use isFutureDate or isPastDate function
    if (!dateStrOrObject)
        return false;
    var dt = {};
    if (!utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt))
        return false;
    today = new Date();
    today.setHours(0, 0, 0, 0);
    if (dt.date)
        dt.date.setHours(0, 0, 0, 0);
    if (returnDate)
        returnDate.date = dt.date;
    //creating new date using only current d/m/y. as td.date is created with string. otherwise same day selection will not be validated.
    if (isFuture && dt.date && dt.date.getTime && dt.date.getTime() > today.getTime()) {
        return true;
    }
    if (!isFuture && dt.date && dt.date.getTime && dt.date.getTime() < today.getTime()) {
        return true;
    }
    return false;
}

function utiljs_isLeapYear(dateStrOrObject, returnDate) {
    var dt = {};
    if (!dateStrOrObject)
        return false;
    if (utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt)) {
        if (returnDate)
            returnDate.date = dt.date;
        return dt.date.getFullYear() % 4 == 0;
    }
    return false;
}

function utiljs_firstDateLaterThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() > dt2.date.getTime())
        return true;
    return false;
}

function utiljs_isEqual(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() == dt2.date.getTime())
        return true;
    return false;
}

function utiljs_firstDateEarlierThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() < dt2.date.getTime())
        return true;
    return false;
}

전체 코드를 파일로 복사하고 포함하십시오.

도움이 되었기를 바랍니다.

참고 URL : https://stackoverflow.com/questions/5812220/how-to-validate-a-date

반응형