입력 유형 = "날짜"형식을 변경하는 방법이 있습니까?
내 웹 페이지에서 HTML5 요소로 작업하고 있습니다. 기본적으로 입력 type="date"
은 날짜를 YYYY-MM-DD
.
문제는 형식을 다음과 같이 변경할 수 있다는 것입니다. DD-MM-YYYY
?
형식을 변경할 수 없습니다
over the wire 형식과 브라우저의 프레젠테이션 형식을 구분해야합니다.
와이어 형식
HTML5 날짜 입력 사양 받는 지칭 RFC3339 규격 과 동일한 전체 데이터 형식을 지정 : yyyy-mm-dd
. 자세한 내용 은 RFC3339 사양의 섹션 5.6 을 참조하세요.
프레젠테이션 형식
브라우저는 날짜 입력을 표시하는 방법에 제한이 없습니다. 작성 당시 Chrome, Edge, Firefox 및 Opera에는 날짜 지원이 있습니다 ( 여기 참조 ). 모두 날짜 선택기를 표시하고 입력 필드의 텍스트 형식을 지정합니다.
데스크탑 장치
Chrome, Firefox 및 Opera의 경우 입력 필드 텍스트의 형식은 브라우저의 언어 설정을 기반으로합니다. Edge의 경우 Windows 언어 설정을 기반으로합니다. 안타깝게도 모든 웹 브라우저는 운영 체제에 구성된 날짜 형식을 무시합니다. 나에게 이것은 매우 이상한 동작이며이 입력 유형을 사용할 때 고려해야 할 사항입니다. 예를 들어, 운영 체제 또는 브라우저 언어가로 설정된 네덜란드어 사용자 는 익숙한 형식 대신 en-us
표시 01/30/2019
됩니다 30-01-2019
.
Internet Explorer 9, 10 및 11은 유선 형식으로 텍스트 입력 필드를 표시합니다.
모바일 장치
특히 Android 용 Chrome의 경우 형식은 Android 표시 언어를 기반으로합니다. 나는 이것을 확인할 수 없지만 다른 브라우저에서도 마찬가지라고 생각합니다.
이 질문이 제기 된 이후로 웹 영역에서 많은 일이 발생했으며 가장 흥미로운 것 중 하나는 웹 구성 요소 의 랜딩입니다 . 이제 필요에 맞게 설계된 사용자 정의 HTML5 요소를 사용하여이 문제를 우아하게 해결할 수 있습니다 . html 태그의 작동을 재정의 / 변경하려면 shadow dom을 사용하여 빌드하십시오 .
좋은 소식은 이미 많은 상용구를 사용할 수 있으므로 처음부터 해결책을 찾을 필요가 없다는 것입니다. 그냥 확인 사람들이 구축하고 무엇을 거기에서 아이디어를 얻을.
다음과 같은 태그를 사용할 수있는 폴리머에 대한 datetime-input 과 같은 간단한 (그리고 작동하는) 솔루션으로 시작할 수 있습니다 .
<date-input date="{{date}}" timezone="[[timezone]]"></date-input>
또는 원하는 형식과 로케일, 콜백 및 긴 옵션 목록을 사용하여 원하는대로 스타일이 지정된 창의적이고 팝업 완전한 날짜 선택기를 얻을 수 있습니다 (전체 사용자 지정 API를 자유롭게 사용할 수 있습니다!).
표준 준수, 해킹 없음.
더블은-확인 가능 polyfills 무엇인지, 브라우저 / 버전 들이 지원을하고 사용자 기반을 충분히 %를 포함하면 기회는 반드시 사용자의 대부분을 다룰 그래서 ... 그것은 2018 년이다.
도움이 되었기를 바랍니다.
앞서 언급했듯이 공식적으로 형식을 변경할 수 없습니다. 그러나 필드의 스타일을 지정할 수 있으므로 (약간의 JS 도움으로) 원하는 형식으로 날짜를 표시합니다. 이러한 방식으로 날짜 입력을 조작 할 수있는 가능성 중 일부가 손실되지만 형식을 강제하려는 욕구가 더 크다면이 솔루션이 방법이 될 수 있습니다. 날짜 필드는 다음과 같이 유지됩니다.
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
나머지는 약간의 CSS와 JS입니다 : http://jsfiddle.net/g7mvaosL/
데스크톱 용 Chrome과 iOS의 Safari에서 잘 작동합니다 (특히 터치 스크린의 기본 날짜 조작기가 탁월한 IMHO이기 때문에 특히 바람직합니다). 다른 사람을 확인하지 않았지만 Webkit에서 실패 할 것으로 예상하지 않습니다.
- RFC 3339 / ISO 8601 "와이어 형식": YYYY-MM-DD. HTML5 사양에 따르면 이는 양식 제출시 또는 DOM API를 통해 요청 될 때 입력 값에 사용해야하는 형식입니다. 로케일 및 지역 독립적입니다.
- 사용자 인터페이스 컨트롤에 표시되고 사용자 입력으로 허용되는 형식입니다. 브라우저 공급 업체는 사용자의 기본 설정 선택을 따르는 것이 좋습니다. 예를 들어, 언어 및 텍스트 환경 설정 창에서 "미국"지역이 선택된 Mac OS에서 Chrome 20은 "m / d / yy"형식을 사용합니다.
HTML5 사양에는 두 형식을 재정의하거나 수동으로 지정하는 수단이 포함되어 있지 않습니다.
브라우저가 현지 날짜 형식을 사용할 것이라고 생각합니다. 변화가 가능하다고 생각하지 마십시오. 물론 사용자 지정 날짜 선택기를 사용할 수 있습니다.
많은 장애물을 겪은 후 형식을 변경할 수있는 솔루션을 찾았습니다. 몇 가지주의 사항이 있지만 'Jan'또는 '01'을 일관되게 표시하려는 경우 사용할 수 있습니다. Firefox가 아직 기본 날짜 선택기를 전혀 지원하지 않기 때문에 Windows 및 Mac의 Chrome에서만 작동합니다.
https://github.com/northamerican/custom-input-date-format
JS :
function updateDateInputs() {
$('input').each(function() {
var $date = $(this),
date = $date.val().split('-'),
format = ['year', 'month', 'day'];
$.each(format, function(i, v) {
$date.attr('data-' + v, +date[i]);
});
});
}
SASS :
$months: '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12';
@each $month in $months {
$i: index($months, $month);
input[data-month="#{$i}"][data-style="reg"]::-webkit-datetime-edit-month-field:after {
content: "#{$month}";
}
}
마지막 베타 버전의 Google 크롬은 마침내 입력을 사용 type=date
하며 형식은 DD-MM-YYYY
.
따라서 특정 형식을 강제하는 방법이 있어야합니다. HTML5 웹 페이지를 개발 중이며 이제 다른 형식으로 날짜 검색이 실패합니다.
빠른 솔루션 이 필요한 경우 시도해보십시오. yyyy-mm-dd를 "dd- Sep -2016"으로 설정하려면
1) 입력 한 스팬 클래스 근처에 생성 (라벨 역할)
2) Update the label everytime your date is changed by user, or when need to load from data.
Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="d M y" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
After having read lots of discussions, I have prepared a simple solution but I don't want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
As said, the <input type=date ... >
is not fully implemented in most browsers, so let's talk about webkit like browsers (chrome).
Using linux, you can change it by changing the environment variable LANG
, LC_TIME
don't seems to work(for me at least).
You can type locale
in a terminal to see your current values. I think the same concept can be applied to IOS.
eg: Using:
LANG=en_US.UTF-8 /opt/google/chrome/chrome
The date is showed as mm/dd/yyyy
Using:
LANG=pt_BR /opt/google/chrome/chrome
The date is showed as dd/mm/yyyy
You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR
by your locale) to create you own custom locale and format your dates as you want.
A nice more advanced reference on how change default system date is: https://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/ and https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale
You can see you real current date format using date
:
$ date +%x
01-06-2015
But as LC_TIME
and d_fmt
seems to be rejected by chrome ( and I think it's a bug in webkit or chrome ), sadly it don't work. :'(
So, unfortunately the response, is IF LANG
environment variable do not solve your problem, there is no way yet.
It's not possible to change web-kit browsers use user's computer or mobiles default date format. But if you can use jquery and jquery UI there is a date-picker which is designable and can be shown in any format as the developer wants. the link to the jquery UI date-picker is on this page http://jqueryui.com/datepicker/ you can find demo as well as code and documentation or documentation link
Edit:-I find that chrome uses language settings that are by default equal to system settings but the user can change them but developer can't force users to do so so you have to use other js solutions like I tell you can search the web with queries like javascript date-pickers or jquery date-picker
Browsers obtain the date-input format from user's system date format.
(Tested in supported browsers, Chrome, Edge.)
As there is no standard defined by specs as of now to change the style of date control, its not possible to implement the same in browsers.
However, This behavior of obtaining the date format from system settings is better and I strongly suggest, we should not try to override it. The reason is, the users will see the date-input's format same as they have configured in the system/device and which they are comfortable with or matches with their locale.
Remember, this is just the UI format on the screen which users see, in your javascript/backend you can always keep your desired format.
Refer google developers page on same.
I know it's an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do. E.g.
var d="16/09/2019" // date received from card
function filldate(){
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");
}
<input type="date" id="cardexpirydate">
<br /><br />
<input type="button" value="fill the date" onclick="filldate();">
what the code do:
- it splits the date which i get as dd/mm/yyyy (using split()) on basis of "/" and makes an array,
- it then reverse the array (using reverse()) since the date input supports the reverse of what i get.
- then it joins (using join())the array to a string according the format required by the input field
All this is done in a single line.
i thought this will help some one so i wrote this.
참고URL : https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format
'developer tip' 카테고리의 다른 글
Python의 easy_install로 설치된 패키지를 제거하려면 어떻게해야합니까? (0) | 2020.09.30 |
---|---|
macOS Mojave 업데이트 후 Git이 작동하지 않음 (xcrun : 오류 : 잘못된 활성 개발자 경로 (/ Library / Developer / CommandLineTools)) (0) | 2020.09.30 |
클래스 JSON을 직렬화 가능하게 만드는 방법 (0) | 2020.09.30 |
Pandas DataFrame에 한 행 추가 (0) | 2020.09.30 |
자바 스크립트에서 localStorage를 지우시겠습니까? (0) | 2020.09.30 |