How to set datetime on datetime-local via jQuery - javascript

I have datetime-local html control on my form and I need to set date and time on it dynamically via JS or jQuery. How can I do it?
<input type="datetime-local" id="publishDate" required/>
I tried
$("#publishDate").val("2013-3-18 13:00");
$("#publishDate").val("2013-3-18T13:00");
$("#publishDate").val(new Date().toLocalString());
but nothing worked.

This would do the trick
$("#publishDate").val("2013-03-18T13:00");
You need to use 2 digits for the month to make your sample work.

If you want to set the current date, then you can try this:
__Method 1:__
$(document).ready(function(){
$('input[type=datetime-local]').val(new Date().toJSON().slice(0,19));
});
__Method 2:__
function zeroPadded(val) {
if (val >= 10)
return val;
else
return '0' + val;
}
$(document).ready(function(){
d = new Date();
$('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
});
Note: You can replace $('input[type=datetime-local]') with Id or Name or Class of the datetime-local field.
EDIT: d.getMonth() returns a value between 0-11, so to input the proper month 1 needs to be added to the result.

What about?
var now=new Date();
console.log(new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().substring(0,19));

I wrote a jQuery method that sets the current UTC time. It's useful for initializing datetime and datetime-local input fields.
Here's how you would use it to initialize a field.
$('input[type="datetime"]').setNow();
Or pass an argument of true to only set fields with no value.
$('input[type="datetime"]').setNow(true);

Here's a solution in formatting the date using momentjs.
This will get the current date and time
moment().format('YYYY-MM-DDThh:mm:ss.SSS')

Here is a simpler way to do it.
const now = (new Date().toLocaleString("sv-SE") + '').replace(' ','T');
console.log(now);

This component is messed up because it's not specified properly yet. Implementations are likely to be quirky as well.
The right way to do it should be to pass a date object, with JS and DOM it would make no sense to not have this. Doing things with string manipulation is going to invoke Zalgo. Sooner or later it will break with the locale or timezone.
I have looked for something like this and in Chrome 46 found:
$('input[type=datetime-local]').prop('valueAsNumber', Math.floor(new Date() / 60000) * 60000); // 60seconds * 1000milliseconds
If you don't remove the second and milliseconds they will show in the input field.
There is a valueAsDate property as well but mysteriously:
Uncaught DOMException: Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date values.
So they haven't finished implementing it yet or choose a bad name for that property (it shows as null even when something is set though).

for those who have date in string format with "T" character in between,
replace the 10 character (space) with T
with below code:
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
var variable=setCharAt("2022-02-26 16:32",10,"T");
$("#publishDate").val(variable);
but remember that the format must be in "YYYY-MM-DDThh:mm:ss"
the OP has made the mistake of providing date "2013-3-18T13:00"
where as the month should have been "03"

Using moment, you can do the following.
If you want to use the current date.
$("#publishDate").val(moment().format('YYYY-MM-DDTHH:MM'));
If you have a specified date.
$("#publishDate").val(moment(yourDate).format('YYYY-MM-DDTHH:MM'));

Related

add future date to a date gotten from json response

I have a date gotten from json response. I able to filter the date to confirm that it is actual date type but I am not able to set future date to it. Below is my snippet
$rootScope.until= response.data.data.dateReceived;
//return future date
// var targetDate = new Date();
$rootScope.until.setDate($rootScope.until + 60);//adding 60 days but cannot
// So you can see the date we have created
$rootScope.until = $filter("date") ($rootScope.until), 'EEEE, MMMM d, y');
Please how can I add future dates
There seem to be two different mistakes here.
You're trying to use Date functions on a Number.
The function Date#setDate() takes as its argument the day of a
month, not the timestamp itself.
Date vs. Number
Problem
If you used new Date(response.data.data.dateReceived) to convert the number of milliseconds you received into a Date datatype, you would be able to access methods like setDate().
However, with your current code, you're trying to perform setDate() on what — to JavaScript — is just an ordinary number. It might as well be -1, since JavaScript has no idea that your number means anything more than its numeric value.
Solution
Since your input data is in milliseconds (a fact you indicated in the comments), the easiest way to accomplish this would simply be to add milliseconds to your initial timestamp like so:
const SIXTY_DAYS = 5184e6; //1000ms/sec * 3600secs/hour * 24hours/day * 60days
$rootScope.until= response.data.data.dateReceived + SIXTY_DAYS;
Just make sure that the value is a number, not a string, otherwise this will perform concatenation instead of addition.
setDate arguments
Problem
If you do have a variable with a datatype of Date (see above), you would have access to methods like Date.setDate(). However, this method's arguments are a bit different than what your code assumes.
Solution
setDate() takes in as its argument a number of days since the start of the month. If you want to add a number of days, you could do the following:
$rootScope.until= new Date(response.data.data.dateReceived);
$rootScope.until.setDate($rootScope.until.getDate() + 60);
This code will obtain the day of the month for the date, then add 60 days to that value. It will automatically handle the change in the month.

JavaScript Date and Time Picker

I've been searching everywhere but I can't seem to find what I'm looking for. I'm trying to find a basic Date and time picker as well as just a time picker that uses JavaScript.
My page is HTML5 and I know about the input types of datetime-local and time but they don't produce the correct format.
For datetime-local, the date and time is formated as:
yyyy-mm-ddThh:mm
I'm trying to find a way to just have the data saved in the field as mm-dd-yyyy hh:mm am/pm using JavaScript.
The page is simple so the user just fills in the above and then the date and time is stored in an element to be called using document.getElememtById
Same with the time only, looking for just a time JavaScript that uses the 12 hour format and the value is stored in an element called by getElementById.
I found things like libraries which I don't need for this simple page.
HTML5 introduced a bunch of new types you can use on a traditional input.
Browsers can use these types to show you context-specific keyboards (on touch screen devices), provide native input validation, and, in the case things like dates, surface a native date picker.
<input type="date">
Automatically setting today’s date
To automatically set a [type="date"] input to today’s date with vanilla JS, we’ll use the JavaScript Date() object.
First, we’ll get our field (let’s assume it has an ID of #today) and create a new Date() object.
var field = document.querySelector('#today');
var date = new Date();
The [type="date"] field looks different visually depending on where you live and what browser you’re using (it shows dates in local format norms), but the value follows a YYYY-MM-DD format.
We can get each of those values from our date, convert them to a string with toString(), and concatenate them into a single value.
We’ll use getFullYear() to get the year in a four-character format.
We’ll use getMonth() to get the month.
We’ll use getDate() to get the day.
For some absurd reason, the getMonth() method returns the month as a number starting with 0 (January is 0, February is 1, etc.). We need to add 1 to our result to get the correct month.
Because they’re numbers and not strings, both getMonth() and getDate() are missing leading zeros for single digit months/days. We can use the padStart() method to add those if missing.
Our finished result looks like this.
field.value = date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString().padStart(2, 0) +
'-' + date.getDate().toString().padStart(2, 0);
Let’s do a few things:
Add some helper text to our input label on the proper format that we can hide if the date input type is supported.
Add a pattern attribute to validate against for unsupported browsers.
Add a placeholder attribute with the pattern as well.
<label for="today">
The Date
<span class="description"> Please use the YYYY-MM-DD format</span>
</label>
<input
id="today"
type="date"
pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" placeholder="YYYY-MM-DD"
The JavaScript to set the date won’t change, but we can add some additional code to remove the pattern, placeholder, and helper text if not needed.
// Variables
var field = document.querySelector('#today');
var date = new Date();
// If [type="date"] is supported, update the DOM
if (isDateSupported()) {
// Remove attributes
field.removeAttribute('pattern');
field.removeAttribute('placeholder');
// Remove the helper text
var helperText = document.querySelector('[for="today"] .description');
if (helperText) {
helperText.parentNode.removeChild(helperText);
}
}
// Set the value
field.value = date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString().padStart(2, 0) +
'-' + date.getDate().toString().padStart(2, 0);
Here is a working example by Chris Fardinand

Can't Compare dates using jQuery UI's datepicker

Ok, so I am attempting to test if a date is older than today. I am using jQuery UI's Datepicker to parse the date and assign it to a variable:
//Get Date as String
var $strDate = $(".pmt-date").text();
//Parse Date
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Then I get today's date and assign it to a variable:
//Get Today's Date
var $strToday $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
Now I would like to compare $dtDate with $tDate. This is what I have tried:
if($dtDate > $tDate)
{
alert("Payment Date is Greater");
}
else
{
alert("Today's Date is Greater");
}
When I test this, I ALWAYS get the alert "Today's Date is Greater". I can display my two date variables via an alert, and I see the dates in correct format. So why does this comparison fail to work when the parse is working correctly?
Assuming that the field with class "pmt-date" is the datepicker-controlled <input> element, you need to fetch its value with .val(), not .text().
var $strDate = $(".pmt-date").val();
Your next line of code refers to a variable called "$date", not "$strDate", so:
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Once you've got that, you can just directly compare the Date objects:
if ($dtDate < new Date())
There's no need to turn a newly-constructed Date object into a string and then back into a date. I guess you're Date to string and back in order to strip off the time-of-day part of the date, so that's not really a bad way to do it.
In date comparisons, more than means the date comes after, and less than means the date comes before. Older than would imply that the date comes before, and thus you want to use less than
if($dtDate < $tDate)

Is this a good way to check for a valid date in JavaScript?

Please correct or explain how my over-simplification is incorrect as I am not a JavaScript expert.
But I just need to know if an object is a valid date. This will only come from user input (ie, text box).
var is_valid_date = function(date) {
try {
var d = new Date(date);
return true;
}
catch(e) {
return false;
}
}
YOU have to decide what form of dates you want to accept.
Then, once you know what forms you want to accept, you can then check the spec for new Date(str) or date.parse() on MDN and see if it supports exactly what you want and if it does the right things on error conditions (it probably will not). If not, then you will have to do some manual parsing.
If you want further help from us, you will need to specify what forms of date you want to accept.
There are also some browser differences as javascript has moved to support additional date formats and earlier browsers had some inconstencies between them which all means you'll want to build yourself a simple test script with a bunch of legal and illegal date format strings and see if your validity detection does what you want in several browsers. This isn't rocket science to get it right, but it's not trivial either and requires some work unless you only want to accept what the original date object supported (which is unlikely).
If this were my code, I'd probably decide that it's far less work to do manual parsing of your desired input format that you know with 100% certainty will work in all browsers because it's your own manual parsing. I'd probably use a regex to parse the date and then convert each component to a number and check each component for validity. You can then feed those numeric components to the Date constructor to create the Date object.
If you can tell by now, the built-in date class isn't very useful for user entered input. If you're willing to use a library for this, the date.js library has a ton of useful functionality in this regard.
Here's an example of a manual parsing function that accepts these US formats:
mm-dd-yyyy
mm dd yyyy
mm/dd/yyyy
JS Code:
function checkDate(str) {
var matches = str.match(/(\d{1,2})[- \/](\d{1,2})[- \/](\d{4})/);
if (!matches) return;
// parse each piece and see if it makes a valid date object
var month = parseInt(matches[1], 10);
var day = parseInt(matches[2], 10);
var year = parseInt(matches[3], 10);
var date = new Date(year, month - 1, day);
if (!date || !date.getTime()) return;
// make sure we have no funny rollovers that the date object sometimes accepts
// month > 12, day > what's allowed for the month
if (date.getMonth() + 1 != month ||
date.getFullYear() != year ||
date.getDate() != day) {
return;
}
return(date);
}
And a demo with some test cases: http://jsfiddle.net/jfriend00/xZmBY/
If you want the Euro format, it's a trivial matter to switch the code to that. In either case, you have to decide which format you accept, code for it and then communicate to the user which format is required. If you think this is messy, then perhaps you will see why so many sites use a date calendar picker that doesn't have this complexity.
Please correct or explain how my over-simplification is incorrect as I am not a JavaScript expert.
But I just need to know if an object is a valid date. This will only come from user input (ie, text box).
Here's why it's an oversimplification.
First of all, it sounds like you really want to check the validity of a string representation of a Date object. This is not particularly useful by itself, because you are going to want to use the date for something in your script, send it to the server, etc.
If you want to use the date in your script, there are caveats.
new Date('2020-10-10') // Fri Oct 09 2020 20:00:00 GMT-0400 (EDT)
If you want to pass it to the server, you'll need to do more than just check validity– you'll need to use a format that your server side code can interpret.
If that's the case, you could consider normalizing the string into a format of your choice. You'd want to be able to create equivalent dates from the normalized strings in both your client and server side code. For simplicity, the format can be human-readable (not a timestamp), and you can replace the value of the text input with the normalized string.
Checking the validity of the string can simply be a part of normalization... have the function return false or an empty string if the input was bad, don't change the text input's value, and instead show a message indicating that the value is invalid:
// assume `birthday` is a text input.
birthday.onblur = function() {
var dateString = normalizeDate(birthday.value);
if (dateString) {
validator.style.display = 'none';
birthday.value = dateString;
} else {
validator.style.display = 'block';
}
};
Here's an example of what the normalizeDate function might look like. This example uses the format 'yyyy-mm-dd', you can change it to suit your needs.
function normalizeDate(dateString) {
// If it's not at least 6 characters long (8/8/88), give up.
if (dateString.length && dateString.length < 6) {
return '';
}
var date = new Date(dateString),
month, day;
// If input format was in UTC time, adjust it to local.
if (date.getHours() || date.getMinutes()) {
date.setMinutes(date.getTimezoneOffset());
}
month = date.getMonth() + 1;
day = date.getDate();
// Return empty string for invalid dates
if (!day) {
return '';
}
// Return the normalized string.
return date.getFullYear() + '-' +
(month > 9 ? '' : '0') + month + '-' +
(day > 9 ? '' : '0') + day;
}
Here's the obligatory live demo.
new Date() doesn't throw an exception if month>12 for example, you can use Date.parse() and test the returned value with isNaN()

Validating a UK date using Javascript/jQuery

I have two jQuery datepickers that once changed, will trigger some ajax to grab all information between the two dates.
I want to run some code to check that the first date is smaller than the second, by converting to a date using this code:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
return new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
}
This works great, but the problem is even if I enter a date of '50/08/2011' it still validates and converts that to a Javascript date, I believe by adding the additional number of days to the start date.
Is there a way to properly validate this please?
Thanks!
you can validate using a jquery masked plugin,you can check it http://digitalbush.com/projects/masked-input-plugin/
For working with dates you can try to use datejs library. It has many features including validating dates. To solve your problem you can use Date.validateDay method. Also you can use datejs to compare dates.
hm... I guess a plugin would be a better solution, but for what it's worth:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
var newDate = new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
return newDate.getDate() == Number(dateStr[0]) && newDate.getMonth() == Number(dateStr[1]) - 1? newDate : null;
}
returns null if the date carries over to the next month.
Edit
New code :P

Categories

Resources