Programing

dd-mm-yyyy 문자열을 날짜로 변환

lottogame 2020. 5. 25. 08:03
반응형

dd-mm-yyyy 문자열을 날짜로 변환


다음을 사용하여 dd-mm-yyyy 형식의 문자열을 JavaScript의 날짜 객체로 변환하려고합니다.

 var from = $("#datepicker").val();
 var to = $("#datepickertwo").val();
 var f = new Date(from);
 var t = new Date(to);

("#datepicker").val()dd-mm-yyyy 형식의 날짜를 포함합니다. 다음을 수행하면 "잘못된 날짜"가 표시됩니다.

alert(f);

'-'기호 때문입니까? 이걸 어떻게 극복 할 수 있습니까?


"-"로 분할

문자열을 필요한 부분으로 구문 분석하십시오.

var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])

정규식 사용

var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))

왜 정규식을 사용하지 않습니까?

하이픈으로 구분 된 세 부분으로 구성된 문자열로 작업한다는 것을 알고 있기 때문입니다.

그러나 다른 문자열 내에서 동일한 문자열을 찾고 있다면 정규식을 사용하는 것이 좋습니다.

재사용

샘플 코드에서 또는 코드베이스의 다른 곳에서이 작업을 두 번 이상 수행하므로 함수로 묶으십시오.

function toDate(dateStr) {
  var parts = dateStr.split("-")
  return new Date(parts[2], parts[1] - 1, parts[0])
}

다음과 같이 사용 :

var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)

또는 함수에서 jQuery를 신경 쓰지 않으면 :

function toDate(selector) {
  var from = $(selector).val().split("-")
  return new Date(from[2], from[1] - 1, from[0])
}

다음과 같이 사용 :

var f = toDate("#datepicker")
var t = toDate("#datepickertwo")

현대 JavaScript

좀 더 현대적인 JS를 사용할 수 있다면 배열 파괴는 좋은 터치입니다.

const toDate = (dateStr) => {
  const [day, month, year] = dateStr.split("-")
  return new Date(year, month - 1, day)
}

정규식 예 :

new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );

또 다른 가능성 :

var from = "10-11-2011"; 
var numbers = from.match(/\d+/g); 
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);

숫자를 일치시키고 순서를 바꿉니다


var from = $("#datepicker").val(); 
var f = $.datepicker.parseDate("d-m-Y", from);

moment.js 예제 사용 :

var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)

Date()다음과 같이 객체 의 괄호 안에 날짜를 쓸 수도 있습니다 .

new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)

이 형식을 사용하십시오. myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00


나의 경우에는

new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))

결과 : Mon Nov 02 2015 04:40:13 GMT + 0100 (CET) 그런 다음 .getTime ()을 사용하여 밀리 초로 작업


외부 라이브러리를 사용하여 도움을 줄 수 있습니다.

http://www.mattkruse.com/javascript/date/source.html

getDateFromFormat(val,format);

JavaScript 참조 DateTime 문자열 구문 분석


모든 소소한 날짜 관련 문제에 대해서는 Datejs살펴보십시오 . parseDate 함수로도 해결할 수 있습니다.


Regexp를 사용할 수 있습니다.

var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
    from = new Date(
        parseInt(result[3], 10), 
        parseInt(result[2], 10) - 1, 
        parseInt(result[1], 10)
    );
}

허용되는 답변에 버그가 있습니다.

var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])

Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:

var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z

Which is probably not the desired result.

The reason for this is explained on the MDN site:

Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1).


A better way to solve the problem is:

const stringToDate = function(dateString) {
  const [dd, mm, yyyy] = dateString.split("-");
  return new Date(`${yyyy}-${mm}-${dd}`);
};

console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z

console.log(stringToDate('77-78-7980'));
// Invalid Date

This gives you the possibility to handle invalid input.

For example:

const date = stringToDate("77-78-7980");

if (date === "Invalid Date" || isNaN(date)) {
  console.log("It's all gone bad");
} else {
  // Do something with your valid date here
}

new Date().toLocaleDateString();

simple as that, just pass your date to js Date Object

참고URL : https://stackoverflow.com/questions/7151543/convert-dd-mm-yyyy-string-to-date

반응형