I just have a simple line of code like this:
<input type='date' min='1899-01-01' max='2000-01-01'></input>
Is there a simple way to set the max date to "today" instead of 2000-01-01? Or do I have to use Javascript to do this?
JavaScript only simple solution
datePickerId.max = new Date().toISOString().split("T")[0];
<input type="date" id="datePickerId" />
// below trick also works! Thanks jymbob for the comment.
datePickerId.max = new Date().toLocaleDateString('fr-ca')
You will need Javascript to do this:
HTML
<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>
JS
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = yyyy + '-' + mm + '-' + dd;
document.getElementById("datefield").setAttribute("max", today);
JSFiddle demo
In lieu of Javascript, a shorter PHP-based solution could be:
<input type="date" name="date1" max="<?= date('Y-m-d'); ?>">
Javascript will be required; for example:
$(function(){
$('[type="date"]').prop('max', function(){
return new Date().toJSON().split('T')[0];
});
});
JSFiddle demo
toISOString() will give current UTC Date. So to get the current local time we have to get getTimezoneOffset() and subtract it from current time
document.getElementById('dt').max = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split("T")[0];
<input type="date" min='1899-01-01' id="dt" />
Is you don't want to use external scripts, but rather set the max limit right in the HTML input element, inline as so:
<input type="date" max="3000-01-01" onfocus="this.max=new Date().toISOString().split('T')[0]" />
I've intentionally added the max attribute with a date far into the future, because it seems Chrome browser change the width of the field once a max attribute is set, so to avoid that, I had it pre-set.
See live demo
I am using Laravel 7.x with blade templating and I use:
<input ... max="{{ now()->toDateString('Y-m-d') }}">
Yes, and no. There are min and max attributes in HTML 5, but
The max attribute will not work for dates and time in Internet Explorer 10+ or Firefox, since IE 10+ and Firefox does not support these input types.
EDIT: Firefox now does support it
So if you are confused by the documentation of that attributes, yet it doesn't work, that's why.
See the W3 page for the versions.
I find it easiest to use Javascript, s the other answers say, since you can just use a pre-made module. Also, many Javascript date picker libraries have a min/max setting and have that nice calendar look.
An alternative to .split("T")[0] without creating a string array in memory, using String.slice():
new Date().toISOString().slice(0, -14)
datePickerId.max = new Date().toISOString().slice(0, -14);
<input type="date" id="datePickerId" />
Examples with jQuery and JavaScript:
$('#arrival_date').attr('min', new Date().toISOString().split('T')[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" name="arrival_date" id="arrival_date" class="form-control" aria-label="...">
document.getElementById('arrival_date').setAttribute('min', new Date().toISOString().split('T')[0])
<input type="date" name="arrival_date" id="arrival_date" class="form-control" aria-label="...">
it can be useful :
If you want to do it with Symfony forms :
$today = new DateTime('now');
$formBuilder->add('startDate', DateType::class, array(
'widget' => 'single_text',
'data' => new \DateTime(),
'attr' => ['min' => $today->format('Y-m-d')]
));
A short but may be less readable version of one of the previous answers.
<script type="text/javascript">
$(document).ready(DOM_Load);
function DOM_Load (e) {
$("#datefield").on("click", dateOfBirth_Click);
}
function dateOfBirth_Click(e) {
let today = new Date();
$("#datefield").prop("max", `${today.getUTCFullYear()}-${(today.getUTCMonth() + 1).toString().padStart(2, "0")}-${today.getUTCDate().toString().padStart(2, "0")}`);
}
</script>
Yes... you have to use Javascript. My solution below is just yet another option which you can pick up.
var today = new Date().toJSON().slice(0, 10);
var date = $('#date-picker');
date.attr('max', today);
Example with React
import Input from "./components/Input";
const DateInput = () => {
const today = new Date().toISOString().split("T")[0];
return <Input type="date" max={today} />
}
export default DateInput;
Template: ejs
Using Node.js, express.js and template System ejs:
<input id="picOfDayDate" type="date" name="date-today"
value="<%= new Date().toISOString().split("T")[0] %>"
min='1995-06-16'
max="<%= new Date().toISOString().split("T")[0] %>"
class="datepicker"
>
I also had same issue .I build it trough this way.I used struts 2 framework.
<script type="text/javascript">
$(document).ready(function () {
var year = (new Date).getFullYear();
$( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate:
0});
});
</script>
<s:textfield name="effectiveDate" cssClass="input-large"
key="label.warrantRateMappingToPropertyTypeForm.effectiveDate"
id="effectiveDateId" required="true"/>
This worked for me.
Related
I want to refine my value today but i cant set. Can help me!
<input type="date" name="start" value="2022-12-25"/>
<input type="date" name="end" value="2022-12-25"/>
I want to refine my value today but i cant set. Can help me!
You can try to set the default date with js:
<input type="date" name="start" />
<input type="date" name="end" />
#section Scripts{
<script>
$(function(){
document.getElementsByName('start')[0].valueAsDate = new Date();
document.getElementsByName('end')[0].valueAsDate = new Date();
})
</script>
}
result:
the information you provided is not sufficient. Provide which language/technology you are working, i figured it out that you are looking for help in Microsoft technology stack.
Coming to the point you want to print/show Current Datetime value, for that, According to me Create variable storage Current Datetime and bind it to the Html
for Ex.
var CurrentDateTime = DateTime.now;
this will set Current date time to the variable and in HTML MVC if you are using razor view / pages
you just need to bind that value to it.
there are multiple ways for that.
but here i would like to GO with ViewBag approach
you can do like following
ViewBag.CurrentDatetime = DateTime.Now;
And in your UI cshtml file
retrieve that stored value from ViewBag like following
#{
var CurrentDatetime = ViewBag.CurrentDatetime;
}
<input type="date" name="end" value=#CurrentDatetime/>
Note: If you not find this answer Helpful, i am requesting you to Provide some Detailed and precise Explanation regarding what you exactly looking for.
Thanks.
There is a similar question which limits the number of characters for allowed in a form input.
In my case I want to limit the number of digits that can be added after the decimal point to 2 digits.
<input type="text" maxlength="2"/>
Is there a way to limit the digits after a decimal point (.) ?
As I am not aware of any way to do it in HTML…
Here is how I'll do it with some JavaScript, using a RegEx to delete the extra decimals:
var myInput = document.querySelector('#fixed2');
myInput.addEventListener("keyup", function(){
myInput.value = myInput.value.replace(/(\.\d{2})\d+/g, '$1');
});
<input id="fixed2" type="text" />
Note that I used the keyup event here, so that you can see the automatic deletion. But it works great with input too!
⋅
⋅
⋅
We could generalize this method to work with multiple inputs, using a custom attribute like decimals:
(I'm using input event here, so you see the difference)
var myInputs = document.querySelectorAll('.fixed');
myInputs.forEach(function(elem) {
elem.addEventListener("input", function() {
var dec = elem.getAttribute('decimals');
var regex = new RegExp("(\\.\\d{" + dec + "})\\d+", "g");
elem.value = elem.value.replace(regex, '$1');
});
});
<input class="fixed" type="text" decimals="2" placeholder="2 decimals only" />
<br><br>
<input class="fixed" type="text" decimals="3" placeholder="3 decimals only" />
Hope it helps.
I think best option is to resovle this with jQuery validator, where you can add requirments for each field that you are using. If you are trying to resovle this with HTML5 it might happen that in some browsers it will not work in a way you want.
Check this --> https://jqueryvalidation.org/
--> https://jqueryvalidation.org/maxlength-method/
If you are comfortable using scripts, then you may try the following approach:
$(document).ready(function() {
$("input").on("blur", function() {
$(this).val(parseFloat($(this).val()).toFixed(2));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="0.01" min="0" />
The following solution works with number inputs and therefor defends against alphabetical characters (unlike the currently accepted answer):
function limitDecimalPlaces(e, count) {
if (e.target.value.indexOf('.') == -1) { return; }
if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
e.target.value = parseFloat(e.target.value).toFixed(count);
}
}
<input type="number" oninput="limitDecimalPlaces(event, 2)" />
Note that this cannot AFAIK, defend against this chrome bug with the number input.
I am using below HTML tag:
<input type="time" />
In Chrome, Its showing PM/AM format, can we restrict to display 24 format always.
I dont want to use HTML5 tag
As stated in this answer not all browsers support the standard way. It is not a good idea to use for robust user experience. And if you use it, you cannot ask too much.
Instead use time-picker libraries. For example: TimePicker.js is a zero dependency and lightweight library. Use it like:
var timepicker = new TimePicker('time', {
lang: 'en',
theme: 'dark'
});
timepicker.on('change', function(evt) {
var value = (evt.hour || '00') + ':' + (evt.minute || '00');
evt.element.value = value;
});
<script src="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
<link href="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>
<div>
<input type="text" id="time" placeholder="Time">
</div>
More info about the time input can be found on MDN Web Docs
<!DOCTYPE html>
<html>
<body>
Time: <input type="time" id="myTime" value="16:32:55">
<p>Click the button to get the time of the time field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myTime").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
I found that by setting value field (not just what is given below) time input will be internally converted into the 24hr format.
You can't do it with the HTML5 input type. There are many libs available to do it, you can use momentjs or some other jQuery UI components for the best outcome.
In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.
According to the Docs input[time]: https://docs.angularjs.org/api/ng/input/input%5Btime%5D
it should be enough to use the input type time and bind it to a date oject, however it doesn't work as I'd expect it.
<input ng-model="time" type="time" placeholder="HH:mm" min="08:00" max="17:00" required >
and
$scope.time = new Date();
as a Result I'd like to see just the HH:mm within the input field.
Here's a jsfiddle to play around:
http://jsfiddle.net/U3pVM/7314/
I think you need at least Angular 1.3.0 beta for this to work, as it looks like it was introduced then.
Changelog:
...
Features
input: support types date, time, datetime-local, month, week
(46bd6dc8, #5864)
....
You could achieve that, follow my code,
http://plnkr.co/edit/60aiH0eJ8ee0FlEsQE2m?p=info
Basically i use momentjs, and set seconds and milliseconds to zero, that way browser will not render that.
moment().second(0).milliseconds(0).toDate();
Here's an example of how to use input="time" with angularJS and bind it using ng-model directive
HTML: <input type="time" ng-model="myTime"/>
in the controller, we assign time came from database to date a new object
$scope.myTime = new Date(response.data.start_time);
this will parse the full date as a time HH:MM:SS Successfully
Change $scope.time = new Date(); in your code to:
var d = new Date();
$scope.time = d.getHours() + ':' + d.getMinutes();
Working code: http://jsfiddle.net/bitsmith/asjv8ycq/1/
AngularJS Element Directive input[time] is used to create HTML time input with time validation and transformation.
The input must be provided in the format ISO-8601, i.e local time format HH:mm:ss, for example 15:35:10
The data model must be a Date Object, timezones used to read/write Date instance are defined using ngModel
Syntax
<input type="time"
ng-model="string"
[name="string"]
[min="string"]
[max="string"]
[required="string"]
[ng-required="string"]
[ng-change="string"]>
Use following code to bind time and for getting other attribute related to input type time.
<!doctype html>
<html lang="en">
<head>
<title>AngularJS Directives : input[time]</title>
<script src="angular.js"></script>
<style>
b{font-family:Papyrus; color:#fa4b2a; font-size: 20px;}
</style>
</head>
<body ng-app="timeDemo">
<script>
angular.module('timeDemo', [])
.controller('timeController', ['$scope', function($scope) {
$scope.sample = {
value: new Date(1999, 0, 1, 15, 30, 0)
};
}]);
</script>
<form name="demoForm" ng-controller="timeController as timeCtrl">
<label for="sampleInput">Select a time from 6 am to 6 pm</label>
<input type="time" id="sampleInput" name="input" ng-model="sample.value"
placeholder="HH:mm:ss" min="06:00:00" max="18:00:00" required />
<!-- min 6 am and max 6 pm i.e 18:00 -->
<div role="alert">
<span class="error" ng-show="demoForm.input.$error.required">
Input is Required!</span>
<!-- Required Error -->
<span class="error" ng-show="demoForm.input.$error.time">
Input Date is not Valid!</span>
<!-- Validation Error -->
</div>
<i>value = <b>{{sample.value | date: "HH:mm:ss"}}</b></i><br/>
<i>demoForm.input.$valid = <b>{{demoForm.input.$valid}}</b></i><br/>
<i>demoForm.input.$error = <b>{{demoForm.input.$error}}</b></i><br/>
<i>demoForm.$valid = <b>{{demoForm.$valid}}</b></i><br/>
<i>demoForm.$error.required = <b>{{!!demoForm.$error.required}}</b></i><br/>
</form>
</body>
</html>
Below will ensure your input always has HH:mm format.
$scope.time = return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes());
Additionally, a function can be written in the controller end to format all Date values to be fed in time input
getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
if (val != undefined) {
date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
}
}
I just upgraded an ASP.Net MVC application to MVC-4. The field editor for inputs based on DateTime values now include's the HTML-5 type="date" attribute/value declaration.
Now, when viewing in Chrome, my date inputs show up with "mm/dd/yyyy" in the input field:
Even when I pass in a correctly-formatted date with the value attribute:
<input value="2012/10/02" type="date"/>
I'm still getting "mm/dd/yyyy" in the input box, which is there until the user manually changes the value.
The problem appears to be with Chrome, and is independent of my back-end framework. See this problem in action: jsFiddle
...big problem for editing records, of course. If the user pulls up a record that already has a valid date, it won't pass validation on submit, unless s/he clicked into the field and reset the value manually.
No problems with the other browsers.
Is this a Chrome bug? Or have I missed something about the way the HTML-5 date field is supposed to work?
UPDATE
See this revise fiddle: http://jsfiddle.net/HudMe/5/ It has both an HTML-4 and an HTML-5 date input, each with "10/01/2012" set as the value on page-load.
Click into either date field.
The Javascript should pup up an alert with the value of the field for that element.
Because a valid date has been passed in with the value attribute, this should show "10/01/2012", but in Chrome, for the HTML-5 date field, nothing shows. Reset this value by hand, then click again, and it will now show.
The value from the HTML5 field shows and alerts as expected without adjustment after pageload in Safari, Firefox, IE and Opera.
Note on accepted answer:
For other users of Asp.net mvc-4, you can adjust the display format with the [DisplayFormat] attribute on the DateTime field declaration in your view-model. (found at https://stackoverflow.com/a/12634470/613004 )
In chrome to set the value you need to do YYYY-MM-DD i guess because this worked : http://jsfiddle.net/HudMe/6/
So to make it work you need to set the date as 2012-10-01
Had the same problem. A colleague solved this with jQuery.Globalize.
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/globalize.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/cultures/globalize.culture.nl.js"></script>
<script type="text/javascript">
var lang = 'nl';
$(function () {
Globalize.culture(lang);
});
// fixing a weird validation issue with dates (nl date notation) and Google Chrome
$.validator.methods.date = function(value, element) {
var d = Globalize.parseDate(value);
return this.optional(element) || !/Invalid|NaN/.test(d);
};
</script>
I am using jQuery Datepicker for selecting the date.
I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works.
Tested in chrome, firefox, and Edge
today:function(){
var today = new Date();
var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
var y = today.getFullYear();
var x = String(y+"-"+m+"-"+d);
return x;
}
I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
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:
If you are dealing with a table and one of the dates happens to be null, you can code it like this:
#{
if (Model.SomeCollection[i].date_due == null)
{
<td><input type='date' id="#("dd" + i)" name="dd" /></td>
}
else
{
<td><input type='date' value="#Model.SomeCollection[i].date_due.Value.ToString("yyyy-MM-dd")" id="#("dd" + i)" name="dd" /></td>
}
}