HTML5 Time Element in Form with Milliseconds - html

There are several examples of HTML5 form options on this page, including the "time" element. Is it possible to force the time element to include a millisecond component?
I'm not concerned for the fallback option where a plain text box is used.

This works:
<input type="time" step="0.001"></input>
Live preview: http://jsbin.com/giqikelumu/edit?html,output

Simply use the step attribute. In case of a input type="time". The step attribute defaults to 60 (1 means 1 second). But you can also set fractions.
<input type="time" step="any" />

As its an input tag, the value can be entered into it by the user then using the step attribute as stated above will surely help.
What if this input is in the form and value can come from some API cal and is given to the form to show it. It can be changed too. If the requirement then is to show or not show the second or millisecond part we can do the following.
When second and millisecond is required
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());
}
}
When second and millisecond is NOT required
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());
}
}

Related

Check date is correct + regex Angular4

I have a form in Angular4, with 2 dates: started, finished.
I want to check that the format date is dd/mm/yyyy.
I wrote:
<input pattern="((0)*[1-9]|[1-2][0-9]|(3)[0-1])(\/)(((0)*[1-9])|((1)[0-2]))(\/)\d{4}$" [(ngModel)]="filterDateStart" class="form-control" type="date" id="filterDateStart" name="filterDateStart" clrDate>
<input pattern="((0)*[1-9]|[1-2][0-9]|(3)[0-1])(\/)(((0)*[1-9])|((1)[0-2]))(\/)\d{4}$" [(ngModel)]="filterDateEnd" class="form-control" type="date" id="filterDateEnd" name="filterDateEnd" clrDate>
Then when I write invalid dates , my html doesn't say anything... I can send this form.
Then I need to check these dates.
1º Date start < date end
2º Ranges valid -> (30/20/2018) or (32/12/2018)
I see the library moment.js, but my boss says that I don't should be it. thanks, sorry for my english.
Don't use regexes, rely on the Date API :
const valid = '12/12/2018';
const invalid1 = '12/12';
const invalid2 = '12.12.2018';
const invalid3 = 'foo';
function parseDate(date) {
try {
// Make your business logic here. Examples : all must be defined and numbers, and separated with a /
const [d, m, y] = date.split('/');
if (!d || !m || !y) throw new Error();
if(isNaN(d) || isNaN(m) || isNaN(y)) throw new Error();
return new Date(y, m, d);
} catch(err) {
return 'Invalid date';
}
}
console.log(parseDate(valid));
console.log(parseDate(invalid1));
console.log(parseDate(invalid2));
console.log(parseDate(invalid3));
With that you can create a custom validator, that will be a lot more explicit than using a pattern.

How to get the previous value in (input) event in angular 4

I am trying to add the value and also need to remove the previous value by comparing with a new value.
var total = [];
onSearchChange(event) {
total.push(event);
var sumNumber = total.reduce(
(acc, cur) => acc + Number(cur),
0
);
console.log("get all the changed value, I need to remove the previous values in the total list");
}
<input type='number' (input)="onSearchChange($event.target.value)" />
I don't know if the event itself retains the previous value. You can create a component property to hold the previous value and set it in every input event.
<input id="inputId" type="number" value=23 (input)="foo($event.target.value)">
// have some default value only if you want
previousValue: number
foo(value) {
console.log("previous value ", this.previousValue);
console.log("new value ", value);
this.previousValue = value
}
ngAfterViewInit() {
this.previousValue = parseInt((<HTMLInputElement>document.getElementById('inputId')).value)
}
https://stackblitz.com/edit/angular-ufd15s?file=src%2Fapp%2Fapp.component.ts
You can also add a helper event listener keydown (which seems unnecessary but just saying) on the input element. keydown will occur before input so with keydown you can grab the previous value. https://stackblitz.com/edit/angular-sjxvgp?file=src%2Fapp%2Fapp.component.ts

Adding two javascript functions(depending on input)

I have put together a calculator what calculates a price, depending on user input. It works fine with one input, but now I have to scale it a little with a second user input. But here's the catch: the user might not want to put anything to the field, so it will be empty. And that's the thing that brakes my code. I could duplicate the calculator function and return the values and add those two together in a third function, but it will not work when there's an empty value.
Just for the sake of it, some trivial HTML code:
//When I only calculate with this user input, its easy
<input type="text" id="rocktext"><br>
// But how to consider this and do the same exact calculations like with the
//first one and add those two result together?
<input type="text" id="rocktext2"><br>
The code in the end should look like:
Take first user input, calculate the price(like in code below)
IF(!!) there is a second user input, calculate the price and add it to
the first one
Am I being a moron to try it with JS or just a moron in the firstplace?
Hope to hear from You, guys!
J.
The initial JS code is as follows:
function priceCalc() {
var inputs = document.getElementById("rocktext").value;
var length = inputs.length;
var accept = 6;
var initPrice = 8;
if (inputs<=accept){
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = initPrice + " dollars";
//I can also return the the value calculated here like so:
//retVal = initPrice;
}
else {
var intLength = parseInt(length, 10);
var lengthGap = intLength - accept;
var totals = lengthGap * 0.8 + initPrice;
var prec = totals.toPrecision(3);
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = prec + " dollars";
// Here also the return clause can be possible with the calculation result like so:
//retVal = prec;
}
// And the final return as an alternative to the innerHTML :
// return retVal;
}
Making it scalable, you can add a class to all the inputs which may be in the function (something like calcInput), so you iterate all of them and if the value isn't empty (and if it's a valid number), you put it in the calculation.
Or you can just verify if the second input is empty, if so, calls functionOne, if not, calls functionTwo:
function twoDifferentWays() {
var valueOne = document.querySelector("#rocktext").value;
var valueTwo = document.querySelector("#rocktext2").value;
if (!!valueTwo && !isNaN(valueTwo)) {
callsFunctionOne(valueOne, valueTwo);
} else {
callsFunctionTwo(valueOne, valueTwo);
}
}

Disable certain dates from html5 datepicker

Is it possible to disable dates when I use
I want to disable current date for one scenario and future dates for other scenario.
How should I disable the dates?
You can add a min or max attribute to the input type=date. The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.
<input name="somedate" type="date" min="2013-12-25">
The min and max attributes must be a full date; there's no way to specify "today" or "+0". To do that, you'll need to use JavaScript or a server-side language:
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("somedate")[0].setAttribute('min', today);
http://jsfiddle.net/mblase75/kz7d2/
Ruling out only today, while allowing past or future dates, is not an option with here. However, if you meant you want tomorrow to be the min date (blanking out today and all past dates), see this question to increment today by one day.
As in all other cases involving HTML forms, you should always validate the field server-side regardless of how you constrain it client-side.
In pure HTML, the only restrictions you can put on dates are its lower and upper bounds through the min and max attributes. In the example below, only the dates of the week I'm posting this question are allowed, other appear greyed out and clicking on them doesn't update the input value:
<input type="date" min="2019-06-02" max="2019-06-08"/>
You can also disable any invalid date by using a few lines of JavaScript, but this doesn't ship with all the native <input type="date"> features like greyed-out dates. What you can do is set the date value to '' in case of an invalid date, an error message could also be displayed. Here is an example of an input that doesn't accept weekend dates:
// Everything except weekend days
const validate = dateString => {
const day = (new Date(dateString)).getDay();
if (day==0 || day==6) {
return false;
}
return true;
}
// Sets the value to '' in case of an invalid date
document.querySelector('input').onchange = evt => {
if (!validate(evt.target.value)) {
evt.target.value = '';
}
}
<input type="date"/>
HTML datepicker (<input type=date>) supports min/max attribute, but it is not widely supported.
At the meantime you may consider using bootstrap-datepicker, v1.2.0 is on github.
References:
W3C spec
You could use this to disable future dates :
Inside you document.ready function, place
//Display Only Date till today //
var dtToday = new Date();
var month = dtToday.getMonth() + 1; // getMonth() is zero-based
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('#dateID').attr('max', maxDate);
and in form
<input id="dateID" type="date"/>
Here is the working jFiddle Demo
For react and similar libraries, you may use this to disable all dates before today.
<input type='date' min={new Date().toISOString().split('T')[0]} >
Depending on what you need, you can also use the step attribute to only enable specific dates - e.g. every Monday, or every other day. You can use it in combination with min and max
e.g. every Monday
<input type="date" step="7" value="2022-04-04">
Every Thursday
<input type="date" step="7" value="2022-04-07">
Every other day
<input type="date" step="2">

How do I input date in forms with xhtml or html4?

well I know it's easier on html5, but I have to use html4 or xhtml and I can't find any info without html5 somehow. Can anyone help and explain me how I can input a date?
<input type="text" name ="sometext">
The normal html4 or xhtml doesn't seem to have the type date as the type of input.
Thanks in advance.
This question has been asked & answered on some other StackOverflow threads, but as I'm hitting the same problem, here's more info.
Using the jQuery DatePicker is a good start, but it does not enforce format or min/max value integrity outside of the actual calendar popup. Meaning, you can type or paste some bad stuff.
Here's 2 links to sites that demo how to do it the "old way" in JS with a function:
http://www.javascriptkit.com/script/script2/validatedate.shtml
http://www.w3resource.com/javascript/form/javascript-date-validation.php
And here's a StackOverflow link to another pretty nice way to do it:
Detecting an "invalid date" Date instance in JavaScript
Personally, I need validation and restriction to min and max date ranges (SQL hates dates before 1/1/1773 and somebody tried that in my app). I'm going to wire up a function that tells me if a date string is valid, and then wire that up to the input's onchange event.
Here's the HTML for mine:
I'm also using ASP.NET and jQuery's DatePicker, so the key element for folks is the onblur event.
Here's the JS for the FixValidDate() function:
var availableDateFormats = ["mmddyyyy","mm/dd/yyyy","mm-dd-yyyy","yyyy/mm/dd","yyyy-mm-dd"];
function FixValidDate(txtDate,nulls, minDate, maxDate) {
//debugger;
formats =
{
'mmddyyyy':{
're':/^(\d{1,2})(\d{1,2})(\d{4})$/,
'month': 1,'day': 2, year: 3
},
'mm/dd/yyyy':{
're':/^(\d{1,2})[/](\d{1,2})[/](\d{4})$/,
'month': 1,'day': 2, year: 3
},
'mm-dd-yyyy':{
're':/^(\d{1,2})[-](\d{1,2})[-](\d{4})$/,
'month': 1,'day': 2, year: 3
},
'yyyy/mm/dd':{
're':/^(\d{4})[/](\d{1,2})[/](\d{1,2})$/,
'month': 2,'day': 3, year: 1
},
'yyyy-mm-dd':{
're':/^(\d{4})[-](\d{1,2})[-](\d{1,2})$/,
'month': 2,'day': 3, year: 1
}
}
dateText = txtDate.value;
matched = false;
for(i=0; i<availableDateFormats.length; i++)
{
f = formats[availableDateFormats[i]];
match = dateText.match(f.re);
if(match)
{
matched = true;
month = match[f.month];
day = match[f.day];
year = match[f.year];
//TODO validate if the numbers make sense
txtDate.value = month+"/"+day+"/"+year;
}
}
if (!matched && nulls) {
txtDate.value = "";
return false;
} else {
var timestamp = Date.parse(txtDate.value);
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
if (minDate != null) {
if (d < minDate) {
txtDate.value = "";
return false;
}
}
if (maxDate != null) {
if (d > maxDate) {
txtDate.value = "";
return false;
}
}
} else {
txtDate.value = "";
return false;
}
}
return true;
}
This is from an old library I've used for JS stuff for about a decade. You could easily find another JS validation function and swap mine out.
In my function, I required to accept a variety of date formats, and if it's a bad format, I blank out the field and keep the user in the same box. You could change that up.
HTML4 doesn't have any tags to input date by default.All you need to do is include third party library like JQUERY.
Checkout this example http://jqueryui.com/datepicker/
The basic input element is all that HTML (other than HTML5) has. You should have a label, with associated markup, for all text input. Normally you should also include information about the expected input format, as this varies by language and culture, e.g.
<label for="birth">Date of birth (day/month year):</label>
<input id="birth" type="text" name="birth" size="10">
You should also pre-check the user input client-side, with JavaScript, to give the user fast response in case of data error. Naturally, the checks should be duplicated server-side.