Input type=date 기본값 - Input type=date gibongabs

문제 설명

날짜의 기본값이 표시되지 않습니다. (Default value for date is not showing)

몇 가지 날짜 형식을 시도했지만 어느 것도 저에게 적합하지 않았습니다. 문제는 프로필 편집에서 다른 필드의 기본값을 표시하려고 하는데 날짜 입력 필드의 기본값이 표시되지 않는다는 것입니다.

 <input type="date" formControlName="birthdate" value="{{patient.birthdate | date:'MM‑dd‑yyyy'}}" id="txtDate" class="form‑control mb‑2 mr‑sm‑2 mb‑sm‑0">

html로 날짜를 표시하면 작동하는 것을 볼 수 있습니다. 이 형식은 내 각도 앱용입니다. {{환자.생년월일 | 날짜:'MM‑dd‑yyyy'}}.

Input type=date 기본값 - Input type=date gibongabs


참조 솔루션

방법 1:

Try to use the format

date:'yyyy‑MM‑dd'

instead of

date:'MM‑dd‑yyyy'

It seems that the input field doesn't show date if not specified in specific format.

Hope it helps

방법 2:

You can set first value when you init formControl or update existing control.

For example:

formControl = new FormControl(this.patient.birthdate);

or

this.formControl.setValue(this.patient.birthdate)

It also works with FromGroup.

(by Roland Iordache、asimhashmi、Kamil Augustyniak)

참조 문서

  1. Default value for date is not showing (CC BY‑SA 2.5/3.0/4.0)

#datetime #css #html #Date #angular

목차

  1. <input type="date"> 객체 정의 - 날짜 인풋
  2. <input type="date"> 객체 구문
  3. <input type="date"> 객체 예제 - 접근
  4. <input type="date"> 객체 예제 - 생성
  5. <input type="date"> 객체 속성
  6. <input type="date"> 객체 메서드

<input type="date"> 객체 정의 - 날짜형 인풋

HTML <input type="date"> 태그(요소) 의미. (IE11 이하는 지원 X)

<input type="date"> 객체 구문

[접근]

var x = document.getElementById("요소ID");

또는,

var x = document.getElementById("폼요소ID").elements;

[생성]

var x = document.createElement("INPUT");

x.setAttribute("type", "date");

<input type="date"> 객체 예제 - 접근

<input type="date" id="hz" value="2019-12-21">

<button onclick="homzzang()">클릭</button>

<p id="demo"></p>

<script>

function homzzang() {

  var x = document.getElementById("hz").value;

  document.getElementById("demo").innerHTML = x;

}

</script> 

결과보기 

<input type="date"> 객체 예제 - 생성

<button onclick="homzzang()">클릭</button>

<script>

function homzzang() {

  var x = document.createElement("INPUT");

  x.setAttribute("type", "date");

  x.setAttribute("value", "2019-12-21");

  document.body.appendChild(x);

}

</script> 

결과보기 

<input type="date"> 객체 속성

autocomplete

날짜 필드의 자동 완성 속성값 설정/반환.

autofocus

페이지 로드될 때 날짜 필드가 자동으로 focus 가져야하는지 여부 설정/반환.

defaultValue

날짜 필드의 기본값 설정/반환.

disabled

날짜 필드의 비활성화 여부 설정/반환.

form

날짜 필드를 포함하는 form에 대한 참조 반환.

list

날짜 필드가 포함된 데이터 목록에 대한 참조 반환.

max

날짜 필드의 max 속성값 설정/반환.

min

날짜 필드의 min 속성값 설정/반환.

name

날짜 필드의 name 속성값 설정/반환.

readOnly

날짜 필드가 읽기 전용인지 여부 설정/반환.

required

양식을 제출하기 전에 날짜 필드를 채워야하는지 여부 설정/반환.

step

날짜 필드의 step 속성값 설정/반환.

type

날짜 필드의 form 요소 유형 반환.

value

날짜 필드의 value 속성값 설정/반환. 

<input type="date"> 객체 메서드

stepDown()

날짜 필드의 값을 지정된 숫자만큼 감소.

stepUp()

날짜 필드의 값을 지정된 숫자만큼 증가. 

※ <input type="date"> 객체는 표준 속성/메서드/이벤트 지원.

Asked 11 years, 1 month ago

Viewed 1.2m times

Given an input element:

<input type="date" />

Is there any way to set the default value of the date field to today's date?

Input type=date 기본값 - Input type=date gibongabs

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

asked Aug 8, 2011 at 13:14

0

Like any HTML input field, the browser will leave the date element empty unless a default value is specified within the value attribute. Unfortunately, HTML5 doesn't provide a way of specifying 'today' in the HTMLInputElement.prototype.value.

One must instead explicitly provide a RFC3339 formatted date (YYYY-MM-DD). For example:

element.value = "2011-09-29"

Input type=date 기본값 - Input type=date gibongabs

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Aug 8, 2011 at 13:19

TakTak

11.1k5 gold badges28 silver badges48 bronze badges

14

The JavaScript Date object provides enough built-in support for the required format to avoid doing it manually:

Add this for correct timezone support:

Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

jQuery:

$(document).ready( function() {
    $('#datePicker').val(new Date().toDateInputValue());
});​

Pure JS:

document.getElementById('datePicker').value = new Date().toDateInputValue();

Input type=date 기본값 - Input type=date gibongabs

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Oct 24, 2012 at 15:16

brianarybrianary

8,7622 gold badges34 silver badges29 bronze badges

29

This relies upon PHP:

<input type="date" value="<?php echo date('Y-m-d'); ?>" />

Input type=date 기본값 - Input type=date gibongabs

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Jul 25, 2012 at 6:37

Isham MohamedIsham Mohamed

1,4851 gold badge9 silver badges2 bronze badges

7

You could fill the default value through JavaScript as seen here:

http://jsfiddle.net/7LXPq/

$(document).ready( function() {
    var now = new Date();
    var month = (now.getMonth() + 1);               
    var day = now.getDate();
    if (month < 10) 
        month = "0" + month;
    if (day < 10) 
        day = "0" + day;
    var today = now.getFullYear() + '-' + month + '-' + day;
    $('#datePicker').val(today);
});

I would probably put a bit of extra time to see if the month and date are single digits and prefix them with the extra zero...but this should give you an idea.

EDIT: Added check for the extra zero.

Input type=date 기본값 - Input type=date gibongabs

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Aug 8, 2011 at 13:28

JeffJeff

4,09722 silver badges32 bronze badges

1

HTML

<input type="date" id="theDate">

JQuery

$(document).ready(function() {
    var date = new Date();

    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    var today = year + "-" + month + "-" + day +"T00:00";       
    $("#theDate").attr("value", today);
});

demo

If you don't want to use jQuery you can do something like this

JS

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;       
document.getElementById("theDate").value = today;

demo

TS

const date = new Date()
const year = date.getFullYear()

let month: number | string = date.getMonth() + 1
let day: number | string = date.getDate()

if (month < 10) month = '0' + month
if (day < 10) day = '0' + day

const today = `${year}-${month}-${day}`    
document.getElementById("theDate").value = today;

Input type=date 기본값 - Input type=date gibongabs

answered Mar 8, 2013 at 19:35

Follow the standard Y-m-d format, if you are using PHP

<input type="date" value="<?php echo date("Y-m-d"); ?>">

Input type=date 기본값 - Input type=date gibongabs

answered Nov 15, 2015 at 7:23

Input type=date 기본값 - Input type=date gibongabs

Shuhad zamanShuhad zaman

2,78027 silver badges29 bronze badges

1

In HTML5 as such, there is no way to set the default value of the date field to today’s date? As shown in other answers, the value can be set using JavaScript, and this is usually the best approach if you wish to set the default according to what is current date to the user when the page is loaded.

HTML5 defines the valueAsDate property for input type=date elements, and using it, you could set the initial value directly from an object created e.g. by new Date(). However, e.g. IE 10 does not know that property. (It also lacks genuine support to input type=date, but that’s a different issue.)

So in practice you need to set the value property, and it must be in ISO 8601 conformant notation. Nowadays this can be done rather easily, since we can expect currenty used browsers to support the toISOString method:

<input type=date id=e>
<script>
document.getElementById('e').value = new Date().toISOString().substring(0, 10);
</script>

answered May 29, 2013 at 8:10

Jukka K. KorpelaJukka K. Korpela

190k36 gold badges257 silver badges376 bronze badges

2

If you're doing anything related to date and time in the brower, you want to use Moment.js:

moment().format('YYYY-MM-DD');

moment() returns an object representing the current date and time. You then call its .format() method to get a string representation according to the specified format. In this case, YYYY-MM-DD.

Full example:

<input id="today" type="date">
<script>
document.getElementById('today').value = moment().format('YYYY-MM-DD');
</script>

answered Oct 15, 2014 at 19:17

1

HTML:

<input type="date" value="2022-01-31">

PHP:

<input type="date" value="<?= date('Y-m-d') ?>">

Date format must be "yyyy-mm-dd"

answered Jun 20, 2021 at 23:01

Input type=date 기본값 - Input type=date gibongabs

DavideDavide

1,5751 gold badge14 silver badges29 bronze badges

Javascript

document.getElementById('date-field').value = new Date().toISOString().slice(0, 10);

Jquery

$('#date-field').val(new Date().toISOString().slice(0, 10));

Another Option

If you want to customize the date, month and year just do sum or sub as your wish 😎 For month is started form 0 that is why need to sum 1 with the month.

function today() {
        let d = new Date();
        let currDate = d.getDate();
        let currMonth = d.getMonth()+1;
        let currYear = d.getFullYear();
        return currYear + "-" + ((currMonth<10) ? '0'+currMonth : currMonth )+ "-" + ((currDate<10) ? '0'+currDate : currDate );
    }

Appy the today function

document.getElementById('date-field').value = today();

$('#date-field').val(today());

answered Apr 4, 2019 at 8:27

Input type=date 기본값 - Input type=date gibongabs

use moment.js to solve this issue in 2 lines, html5 date input type only accept "YYYY-MM-DD" this format. I solve my problem this way.

var today = moment().format('YYYY-MM-DD');
 $('#datePicker').val(today);

this is simplest way to solve this issue.

answered Jun 11, 2015 at 18:17

Input type=date 기본값 - Input type=date gibongabs

Umair KhalidUmair Khalid

2,1411 gold badge19 silver badges27 bronze badges

Simplest working version I tested:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date" name="date">
<script>
    $('#date').val(new Date().toJSON().slice(0,10));
</script>

answered Jan 28, 2021 at 10:50

ZafferZaffer

7639 silver badges24 bronze badges

This is very much simple by applying following code, Using PHP

<input type="date" value="<?= date('Y-m-d', time()); ?>" />

Date function will return current date, by taking date in time().

Input type=date 기본값 - Input type=date gibongabs

answered Nov 6, 2019 at 7:16

Gowtham AgGowtham Ag

1772 silver badges5 bronze badges

1

<input id="datePicker" type="date" />

$(document).ready( function() {
    var now = new Date();
 
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);

    var today = now.getFullYear()+"-"+(month)+"-"+(day) ;


   $('#datePicker').val(today);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="datePicker" type="date" />

answered Aug 31, 2018 at 7:59

Input type=date 기본값 - Input type=date gibongabs

SantanuSantanu

1461 silver badge6 bronze badges

Very Simple, Just use server side languages like PHP,ASP,JAVA or even you can use javascript.

Here is the solution

<?php
  $timezone = "Asia/Colombo";
  date_default_timezone_set($timezone);
  $today = date("Y-m-d");
?>
<html>
  <body>
    <input type="date" value="<?php echo $today; ?>">
  </body>
</html>

Input type=date 기본값 - Input type=date gibongabs

Blazemonger

87.8k26 gold badges137 silver badges178 bronze badges

answered Dec 2, 2012 at 12:01

teshguruteshguru

3,4651 gold badge17 silver badges6 bronze badges

0

Both top answers are incorrect.

A short one-liner that uses pure JavaScript, accounts for the local timezone and requires no extra functions to be defined:

const element = document.getElementById('date-input');
element.valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000;
<input id='date-input' type='date'>

This gets the current datetime in milliseconds (since epoch) and applies the timezone offset in milliseconds (minutes * 60k minutes per millisecond).

You can set the date using element.valueAsDate but then you have an extra call to the Date() constructor.

answered Feb 23, 2019 at 23:05

Input type=date 기본값 - Input type=date gibongabs

rovykorovyko

3,7333 gold badges28 silver badges40 bronze badges

if you need to fill input datetime you can use this:

<input type="datetime-local" name="datetime" 
       value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />

Input type=date 기본값 - Input type=date gibongabs

Tom Fenech

70k12 gold badges98 silver badges133 bronze badges

answered Mar 4, 2014 at 23:58

For NodeJS (Express with SWIG templates):

<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />

answered Dec 28, 2016 at 4:47

CodeValveCodeValve

851 silver badge5 bronze badges

The simplest solutions seem to overlook that UTC time will be used, including highly up-voted ones. Below is a streamlined, ES6, non-jQuery version of a couple of existing answers:

const today = (function() {
    const now = new Date();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    return `${now.getFullYear()}-${month}-${day}`;
})();

console.log(today);  // as of posting this answer: 2019-01-24

Input type=date 기본값 - Input type=date gibongabs

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Jan 24, 2019 at 7:23

DexygenDexygen

12.1k11 gold badges77 silver badges145 bronze badges

1

This is what I did in my code, I have just tested and it worked fine, input type="date" does not support to set curdate automatically, so the way I used to overcome this limitation was using PHP code a simple code like this.

<html>
<head></head>
    <body>
        <form ...>
            <?php
                echo "<label for='submission_date'>Data de submissão</label>";
                echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
            ?>
        </form>
    </body>
</html>

Hope it helps!

Input type=date 기본값 - Input type=date gibongabs

Oliver

25.3k8 gold badges66 silver badges91 bronze badges

answered May 28, 2014 at 12:47

Input type=date 기본값 - Input type=date gibongabs

GumbaGumba

414 bronze badges

1

This is something you really need to do server-side as each user's local time format differs, not to mention each browser behaves different.

Html Date inputs value should be in this format: yyyy-mm-dd otherwise it will not show a value.

ASP CLASSIC , OR VBSCRIPT:

current_year = DatePart("yyyy",date) 
current_month = DatePart("m",date) 
current_day = DatePart("d",date) 

IF current_month < 10 THEN
current_month = "0"&current_month
END IF
IF current_day < 10 THEN
current_day = "0"&current_day
END IF

get_date = current_year&"-"&current_month&"-"&current_day
Response.Write get_date

Output of today's date : 2019-02-08

Then in your html: <input type="date" value="<% =get_date %>"

PHP

just use this: <input type="date" value="<?= date("Y-m-d"); ?>">

answered Feb 8, 2019 at 10:50

Input type=date 기본값 - Input type=date gibongabs

csandreas1csandreas1

2,35424 silver badges44 bronze badges

Even after all these time, it might help someone. This is simple JS solution.

JS

  let date = new Date();
  let today = date.toISOString().substr(0, 10);
  //console.log("Today: ", today);//test
  document.getElementById("form-container").innerHTML =
    '<input type="date" name="myDate" value="' + today + '" >';//inject field

HTML

 <form id="form-container"></form>

Similar solution works in Angular without any additional library to convert date format. For Angular (code is shortened due to common component code):

//so in myComponent.ts 
//Import.... @Component...etc...
date: Date = new Date();
today: String; //<- note String
//more const ...
export class MyComponent implements OnInit {
   //constructor, etc.... 
   ngOnInit() {
      this.today = this.date.toISOString().substr(0, 10);
   }
}
//so in component.html 
<input type="date" [(ngModel)]="today"  />

answered Dec 4, 2019 at 17:08

Input type=date 기본값 - Input type=date gibongabs

StefaDesignStefaDesign

8568 silver badges17 bronze badges

2

A future proof solution, also an alternative to .split("T")[0] that doesn't create a string array in memory, would be using String.slice() as shown below:

new Date().toISOString().slice(0, -14);

A lot of the answers given here, such as slice(0, 10), substring(0, 10) etc will fail in the future.
They use Date.toJSON() which returns Date.toISOString():

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

Once the year becomes 5 digit, these answers will fail.

datePickerId.value = new Date().toISOString().slice(0, -14);
<input type="date" id="datePickerId" />

answered May 6, 2021 at 18:37

Input type=date 기본값 - Input type=date gibongabs

T JT J

42.1k13 gold badges81 silver badges135 bronze badges

by Javascript:

var today = new Date();

document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);

answered Apr 25, 2016 at 10:38

new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)

answered Sep 9, 2016 at 23:37

1

A simple solution:

<input class="set-today" type="date">
<script type="text/javascript">
    window.onload= function() {
        document.querySelector('.set-today').value=(new Date()).toISOString().substr(0,10));
    }
</script>

reformed

4,24510 gold badges59 silver badges83 bronze badges

answered Jul 22, 2018 at 14:37

gajamgajam

4073 silver badges9 bronze badges

4

This returns in the same YYYY-MM-DD format as in ISO but in your local time instead of being UTC.

function getToday() {
    return new Date().toLocaleDateString('en-CA', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

Input type=date 기본값 - Input type=date gibongabs

isherwood

54.2k15 gold badges105 silver badges147 bronze badges

answered Nov 15, 2021 at 1:34

Input type=date 기본값 - Input type=date gibongabs

prefpref

1,0779 silver badges15 bronze badges

Use .defaultValue property of the input:date element to set the default value of the date to today's date.

<input type="date" id="date"/>

window.onload = function loadDate() {
    let date = new Date(),
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    const todayDate = `${year}-${month}-${day}`;

    document.getElementById("date").defaultValue = todayDate;
};

loadDate();

Or make it IIFE/self-called function, on window load

window.onload = (function loadDate() {
    let date = new Date(),
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    const todayDate = `${year}-${month}-${day}`;

    document.getElementById("date").defaultValue = todayDate;
})();

Using defaultValue property gives dynamic advantage, unlike setting the date using the value attribute.

Also, note that the date format must be matched, hence my use of the format for todayDate as:

yyyy-mm-dd

I believe this answers your question, except you want to set a static start and end date. To do this, kindly follow the example below from Mozilla:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date>

answered Aug 22 at 7:19

Input type=date 기본값 - Input type=date gibongabs

If you are using ruby you can use this to set the default value to today's date and time:

<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />

answered Nov 3, 2016 at 16:09

SeanSean

2674 silver badges9 bronze badges