i'm getting an error message on IE8....all other browsers seem to be fine...i've narrowed it down to specific parts of my JavaScript however i cant find a way around it. It seems to be the greater then or less then signs(i could be wrong). Anyone know a way around it(maybe another way of written the sign, writing and gt; wont do it)
example code:
var selectedDate = new Date(document.getElementById("ExpYear").value,document.getElementById("ExpMonth").value)
var nextmonth = selectedDate.setMonth(selectedDate.getMonth());
var last_date_of_selected_date = new Date(nextmonth -1);
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth());
if (today > selectedDate) {<!--i think its the < sign-->
return false;
}
else {
return true;
}
window.onload = function() {
var a = document.getElementById("PaymentForm");
a.onsubmit = function() { return Validate() };
}
var selectedDate = new Date (document.getElementById("ExpYear").value,document.getElementById("ExpMonth").value)
I'm not sure if this solves your issue, but there are at least three problems with this line of code:
the Date constructor expects either zero arguments, one argument containing a timestamp in milliseconds or a string (discouraged) or three arguments containing year, month and day number respectively (possibly followed by four arguments containing hour, minute, second, millisecond)
the month parameter starts at 0 for January, so you probably should decrement the input value (unless you expect the user to enter a number in the range 0 – 11).
a semicolon is missing; though JavaScript interpreters have something called automatic semicolon insertion, it's likely you write better code using semicolons everywhere.
Update: in your second piece of code, the message about a being null or not an object is probably because there's no element with ID PaymentForm, so the line trying to attach an event handler to a will yield an error.
Moreover, you omitted a semicolon after the closing brace (and you probably forgot a closing brace and semicolon after return Validate();).
I see you're missing a semicolon on the selectedDate variable declaration.
Internet Explorer is extremely picky with semicolons.
var selectedDate = new Date (document.getElementById("ExpYear").value,document.getElementById("ExpMonth").value)
Related
I am intending to use a datapicker that does not allow the user to choose previous days before today, but I do want that today itself is available. I did this:
<input
name = "availabilityFrom"
onChange = {(e) => handleDateIn (e.target.value, e.target.name)}
type = "date"
/>
I am working with React so this above is part of a component, that has a state. Then with the value taken, I stored it on a variable to use its valueOf (), and created today´s variable also. Please notice that this.state.filterBy.availabilityFrom holds the value of the target, the selected date on the datapicker.
let today = new Date().valueOf();
let availabilityFromToDate = new Date(this.state.filterBy.availabilityFrom.split("-").join(",")).valueOf();
Then I used a conditional statement to get the desired behavior of the alert:
if (availabilityFromToDate <today && availabilityFromToDate)
{
sweetAlert ("Warning!",
"The entry date must be after the current date";
"warning");
}
It works well, I got so happy when it did. But if I choose today's date, I got the alert message anyway, even if I am not using <= for today.
Maybe I am not understanding the proper use of valueOf (). Been having nightmares about this, haha.
Thanks in advance!: D
My page was working fine and displaying dates and times as expected until I had to add new Date() to avoid the momentjs deprecation warning. Now my date is 5 hours off what it should be.
How can I fix this? vd and v should both be 12:14:26 and, in this instance, fn should be "Seconds ago".
Here is the full code:
var k = key;
var v = obj[key];
var vd = Date.parse(obj[key]));
if (moment(vd).isValid()) {
var fn = moment(vd).fromNow();
v = fn;
}
return {
name: k,
value: v
};
I tried the following based on this post, but it brought back the momentjs deprecation warning:
var vd = new Date(Date.parse(obj[key])).toUTCString();
(and still didn't work)
__________________________________________________________________________________
Threaded comments would be cool
What happens if you just run moment(v)? Should work. – Maggie Pint
It does work, but I get the deprecation warning.
I just looked closer. The format of V is ISO8601 with offset, so you shouldn't be getting a deprecation if you just call moment(v). If you are, try moment(v, moment.ISO_8601) – Maggie Pint
Again, works, but I still get the deprecation warning.
instead of var vd = new Date(Date.parse(obj[key])).toUTCString(); did you try var vd = new Date(Date.parse(obj[key])).toISOString(); ? or even simplier var vd = Date.parse(obj[key]) – user3
With .toISOString() it outputs "Invalid Date". var vd = Date.parse(obj[key]) Is what I had originally, it works as expected but I get the warning.
Your v string appears to use ISO8601 format already? Maybe append the Z, or ask moment to recognise it automatically as UTC when timezone info is missing – Bergi
I just tried var vd = new Date(Date.parse(obj[key] + "Z")); and it works!
In your example, you're passing a value for v as an ISO8601 string without any offset specified. It is ambiguous as to what point in time you are actually talking about.
Because of changes in the ECMAScript specification, the value will be interpreted as UTC by some browsers, and as local time by others.
The way to avoid this ambiguity is to not use the date constructor. Anywhere you have new Date or Date.parse, you're introducing potential differences in behavior. Just use moment's own parser, and be specific as to your intent.
// your input
var v = "2016-09-14T12:14:26.149";
// pick only one of these:
var m = moment(v); // input is local time
var m = moment.utc(v) // input is UTC
// then proceed as normal
if (m.isValid()) {
var fn = m.fromNow();
// etc.
}
If the input is in some other time zone, or has some other specific fixed offset from UTC, then you have various other options for constructing the moment object. But really, don't rely on the Date object to do the parsing. That's the whole point of the deprecation message.
If the input is not always in the expected format (you're looking for invalid inputs, etc.), then you should specify the expected format such that you don't get the deprecation warning. For example:
var m = moment.utc(v, "YYYY-MM-DD[T]HH:mm:ss.SSS");
This particular format is also available as a constant:
var m = moment.utc(v, moment.ISO_8601);
This, and much more are spelled out in the Moment documentation.
It looks like the problem is when you create the date that recovered from the database... because it does not have the timezone... but you know it is "-0500", might be you can add that part hard coded... not ideal but it works
Look at this example:
function getMoment(v){
var vd = moment(v+"-0500");
var result = "?";
if (vd.isValid()){
result = vd.fromNow();
}
return result;
}
Check the getMoment() function, you can just copy and paste and use it in your code.
I'm having difficulty setting a time (duration) value in a datebox. A simple demonstration of the problem is if I do something like:
function initDuration() {
this.d['header Text'] = "Set";
this.d['headerText'] = "Set Duration";
var element = 'input#'+this.element[0].id;
var currentDt = $(element).datebox('getTheDate');
// ***************
var dt = $(element).datebox('parseDate', '%H:%M', this.element[0].value); // Where this.element[0].value = "01:00:00"
// ***************
$(element).datebox('setTheDate', this.element[0].value);
$(element).trigger('datebox', { 'method': 'doset' });
}
dt just contains the current date/time; i.e. jtsage didn't like it. The element is defined (in jade) as:
input.Duration(type="text" name="duration" form="form#{i}"
id="duration#{i}" value="#{map[i].duration}" data-role="datebox"
data-options=
'{"mode":"durationflipbox", "overrideDurationOrder":["h","i"],'
+' "overrideTimeFormat": "%l:%M", "minuteStep":15, "beforeOpenCallback": "initDuration"}')
Also I'm not sure how to change the flipbox title. The 2nd line in initDuration() sets the text for the button but the title still says 'Set Time'.
Because of the first problem the last 2 lines in initDuration() don't do what I want. i.e. they just use the current time, whatever that happens to be.
My apologies that this is going to be an incomplete answer, but it was going to be too long for a comment.
For the title - give "overrideHeaderText" a shot instead. It is entirely possible that I screwed this up at some point, it's not a feature I use in any of my own projects.
Next...
var dt = $(element).datebox('parseDate', '%H:%M', this.element[0].value); // Where this.element[0].value = "01:00:00"
I think I am reading you correctly that "dt" isn't containing what you are expecting. It's because 01:00:00 != %H:%M - to read this "format", you'd need to either use "%H:%M:%S" or "%H:%M:00" (the later ignoring the seconds field).
That said, I think what you are trying to do is set a duration, which, is a little different. There are a few ways to do it - and I'm noticing that there isn't a lot of support to do it functionally. The simplest method, is the set the value of the input, and let datebox handle the math - just be aware that the format you drop into the input must be exactly the same as the output format - it will read it when the control opens (or is initialized if the control is being shown inline - if you are doing it inline, and set the value "later", you can use the 'refresh' method to update it).
For what it's worth, if you really, really, really want to use the setTheDate method, duration modes work by comparing "theDate" (the publicly available date, i.e. setTheDate, getTheDate) with an internal initDate - which is not exposed to the API, but can be found here:
$(element).data('jtsage-datebox').initDate
So, in pseudo-code, for a duration of an hour
myNewDate = $(element).data( 'jtsage-datebox' ).initDate;
myNewDate.setHour( myNewDate.getHour() + 1 );
$(element).datebox( 'setTheDate', myNewDate );
Here's the issue with Podio. I have a calculation field that is set to return a date and it does that well if I only enter a reference to a date field from the item. What I want is for the calculation field to return a null date (as part of an IF statement) and thus leave or make the field empty (and therefore not show up in the calendar).
Something like this:
var date = DateFieldFromPodioItem;
if (whatever) {
moment(date).add(2, "weeks").toDate();
}
else {
//RETURN NULL HERE
};
I have tried setting var zero = null and have it return that. Which yields me an Invalid date error.
I also tried using .setFullYear(null,null,null) along with .setHours(null,null,null,null) to set date and return that. I set date to 1 January 0001 12:00:00.000 AM as was suggested somewhere (I forgot where I read that). The first got me a rather unfriendly: Invalid value datetime.datetime(1753, 9, 12, 22, 43, 41, 128000) (datetime): Dates before year 1900 are not supported. The second did too, with slightly different numbers within the ().
I even tried the rather silly idea of entering no code within else, but that also returns Invalid date.
Any ideas?
----EDIT----
Turns out that even while Podio shows the message Invalid date it lets you save the field anyway and when changing field values so if=false it shows no longer a date in the calculation field. Thanks to Rainer Grabowski for pointing that out to me. If someone #Podio reads this, perhaps fix that?
I'll leave this here to perhaps help someone else, as I have found the answer to my questions on here rather often.
Should work, but I didn't test:
var date = DateFieldFromPodioItem;
var returnValue = null;
if (whatever) {
returnValue = moment(date).add(2, "weeks").toDate();
}
returnValue;
i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5