How to restrict entering old date in angular 6? - html

My code as follows,
ngOnInit() {
let now = new Date();
this.date = formatDate(now, "dd/mm/yyyy",'en-US');
console.log("dateFormat :",this.date);
}
My html:
<input type="date" [min]={{date}} id="App_Date" class="form-control" formControlName="App_Date">
So here Im getting the current date & trying to assign for min. But it is not working. Could somebody please help me with this?
I need to restrict the user to stop entering old dates. How can I achieve this?

Need to remove the timezone properties from the date object using split
ngOnInit() {
let now = new Date();
this.date = new Date().toJSON().split('T')[0];
console.log("dateFormat :",this.date);
}
And remove the curly brackets from the template
<input type="date" [min]="date" id="App_Date" class="form-control" formControlName="App_Date">

Use direct [min]="date" instead of [min]={{date}} in view.
<input type="date" [min]="date" id="App_Date" class="form-control" formControlName="App_Date">

Related

How to set datatime today now for search?

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.

HTML input number type specify first value

I have an HTML input that indicates a year as so:
<input type="number" name="year" placeholder="Year" [max]="presentYear" min="1950">
The input is not required, so by default I simply want the placeholder "Year" to be present. However, as soon as the user clicks on the up or down arrows of the input field, I want the max value to be shown as default, in this case the present year (2018). However, the minimum number is shown instead. This makes no sense for this situation, since the user would have to scroll through 68 years to get to the most common use case.
Is there any way to specify the default "first value" of a number type input field? If it helps answer the question, I'm using Angular 5 for this project.
You can set min to the same value as max initially, and change it for 1950 after the input value has been changed, with the help of ngModel and ngModelChange. The first click on the spinner button will set the current year as the initial value, and the modified min value will allow to change it afterwards.
<input type="number" name="year" placeholder="Year"
[(ngModel)]="year" (ngModelChange)="setMinYear($event)"
[max]="presentYear" [min]="minYear">
export class AppComponent {
presentYear = this.getCurrentYear();
minYear = this.getCurrentYear();
year: number;
private getCurrentYear(): number {
return new Date().getUTCFullYear();
}
public setMinYear(value: number) {
const firstYear = 1950;
if (value >= firstYear) {
this.minYear = firstYear;
} else {
this.minYear = this.presentYear;
}
}
}
The code can be tested in this stackblitz.
in JS:
dateObj: Date = new Date();
year: number = dateObj.getUTCFullYear();
yearModel: number = year;
in HTML
Bind property to your input control , as given in below code it will do for you
<input type="number" name="year"
placeholder="Year"
[(ngModel)] = "yearModel"
[max]="year"
min="1950">
A separate Model prevents the value to go over the current year

How to set option ngx-mydatepicker get MM/yyyy

I don't known how to set the option ngx-mydatepicker to get MM/yyyy. Please help me.
Thank you.
<input class="form-control" style="float:none" placeholder="mm/yyyy" ngx-mydatepicker name="mydate"
model="buyDate" [options]="myDatePickerOptions" #dp="ngx-mydatepicker" [(ngModel)]="date" [ngModelOptions]="{standalone: true}"/>
private myDatePickerOptions: INgxMyDpOptions = {
dateFormat: 'dd/mm/yyyy'
};
Looking at the code for formatting Link to code, the module does not allow you to have dates in that format. You will need to a custom formatting. Take a look at Angular2-moment
What is the initial format of your dates?

Compare html type="date" with typescript new Date() object

I have an html code
<div class="form-group row">
<label class="col-sm-2 col-form-label">Due date: </label>
<div class="col-sm-10">
<input type="date" class="form-control" #due_date>
</div>
</div>
and my typscript code is like this but it never enters the condition, so what should I do?
if(element.due_date <= new Date()){
//if(element.due_time <= new Date().toLocaleTimeString())
console.log(element);
element.notify = true;
}
It could quickly get done using moment.js. I would keep the input model as an ISO string and have moment.js parse it when it compares the dates:
moment(dateInISO).isAfter(anotherDateInISO); // true
Or let moment.js take care of your own different date types :)
According to the template, your component code should be like
export class SomeComponent {
#ViewChild('due_date') due_date: ElementRef;
someMethod() {
const inputDate = new Date(this.due_date.nativeElement.value);
if (inputDate <= new Date()) {
//if(element.due_time <= new Date().toLocaleTimeString())
console.log(this.due_date.nativeElement.value);
// element.notify = true;
}
}
}

Set date input field's max date to today

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.