JavaScript setting dates in textboxes not consistent - javascript

I have a couple of textboxes where a user set a from date and to date from a button click which adds 7 days or substracts 7 to whatever is the current value in each box.
When the page is first loaded the dates that are added into the textboxes are based upon the user belonging to a group. Thus if a user belongs to group A, the from date is a Sunday, but if the user belongs to group B it is a Friday. This logic I set in the page load event in my ASP.Net page.
The situation that is baffling me, is whilst I can set the dates, and get my JavaScript to work with group A, if a switch the user to group B, and click on a button rather expecting the date in from changing from 17th January 10th January, it jumps to 29th December 2014. It seems to be getting a completely differently value initially 5th January 2015.
The JavaScript I have is:
var fromDateIn = new Date(formatDate(document.getElementById('<%=txtFromDate.ClientID%>').value));
var newfromdate = new Date(fromDateIn);
In one of the button event, I have:
function setNewFromDate() {
newfromdate.setDate(newfromdate.getDate() - 7);
document.getElementById('<%= txtFromDate.ClientID%>').value = formatDate(newfromdate);
var toDate = new Date(newfromdate);
document.getElementById('<%= txtToDate.ClientID%>').value = formatDate(toDate.setDate(toDate.getDate() + 6));
}
As I say, everything works perfectly and I get the right dates when the user is one group, but as soon I change the user to another group and set the initial from and to dates, I get this problem. Can anyone please advise I can get consistency in this?
Thanks

There is a problem with the way you are instantiating fromDateIn. You are passing it a value in the format dd/MM/yyyy, but the date constructor that takes a single string value is locale dependent and is treating the input as MM/dd/yyyy. This results in a completely bogus value for fromDateIn that throws everything else off.
You should find a way to determine the year, month and day for the start date (either by parsing it out of the textbox value or having the ASPX logic stuff it into the page somehow). And instantiate the date using the new Date(year, month, day) constructor. (This requires bearing in mind that month is 0-based [i.e. January = 0, February = 1]).

This line:
newfromdate.setDate(newfromdate.getDate() - 7)
Looks like you're trying to move back a week. This will fail. setDate changes only the Day of Month. Can you guess what happens when Day of Month is less than 7?

Related

Is it a day in the current week? Moment JS

I have one problem. Can you tell me how to check does it day in the current week?
I am working on some service for a weather forecast. I have a current day but must check does it in the current week. Only what I know is that I must use 'isSame' function from Moment JS.
This is my line of code.
if(this.conversation.payload.grain==="week" && moment().startOf('week').isSame(this.conversation.payload.forecastTime))
"forecastTime" is a current day. However, the condition is not good and does not enter the if loop.
Thank you!
This is assuming your forecastedDate is an actual javascript date or a moment object.
The isSame function also takes in a granularity parameter.
Just add the 'week' parameter to the isSame method like so:
if(this.conversation.payload.grain==="week" &&
moment().startOf("week").isSame(this.conversation.payload.forecastTime, "week"))
To get the day of the week is easily done with the momentjs library.
This will give you a day of the week based on the locale:
var dayOfWeek = moment(this.conversation.payload.forecastTime).weekday()
For example, if the locale uses Monday as the first day of the week then 0 = Monday and 6 = Sunday. Please keep in mind that the value you recieve will change based on the current locale.
If you don't want the value to change based on locale but always want to receive a Monday-Sunday value use isoWeekday():
var dayOfWeek = moment(this.conversation.payload.forecastTime).isoWeekday()
This will give you an integer 1-7. 1 = Monday, 7 = Sunday.
So, for example, if the above code returned 4, you would know that it was Thursday.
For more details on the weekday(), isoWeekday, and day() functions, check out the momentjs docs.

How to create a Date object from year, month and date strings?

I'm currently just practising JavaScript and I'm trying to create a programme that calculates how many days there are until your next birthday.
I have seen on this site that there is a daysBetween function that I can use to tell the time difference between two dates (I just need to turn these dates into the millisecond value since the 1st Jan 1970).
The problem is that, although one of those dates is the current date (which is easy to convert into its millisecond value), the second is derived from answers the user inputs as a string into a prompt command (there are three different boxes that ask for the year, month and date of their birth). Is there a way I can convert these input strings into a date format that I can then use to find the days between today's date and their next birthday?
Thanks and sorry if this is a stupid question!
Remember in JS that months are indexed from 0, so January === 0.
var date = new Date('2017','5','25'); would be today, assume you have something like:
var userDd = '25';
var userMm = '6'; // User doesn't know the months are indexed at 0.
var userYy = '2017';
var date = new Date(userYy, userMm - 1, userYy);
date.getTime(); // returns the milliseconds value.

Set month view for `bootstrap-datepicker` without setting date

Is there a way to set the current view of the calendar to a specific month/year, without setting a date?
My use case for this is when a user selects a date, I save this date, and clear the calendar by calling clearDates() on it. However, if the selected date fell on a month in the future, (for example, we're in November, and the selected month is next March), then the calendar's view resets back to the current month (November).
I want to set the calendar's view to the last selected month (March), without setting the date, so that the calendar has no date selected, but is showing the days for March of next year (to allow the user to select another date in the last used month, instead of having to click Next bunch of times to get to March again).
You could use the defaultViewDate option for this behavior
$('#datepicker').datepicker({
defaultViewDate: {
year: 2016,
month: 2
}
});
The months int is used like the javascript date month. So january = 0 and december = 11
See example here: http://jsfiddle.net/zcvq0yhh/4/
If you want to change it on the fly there is no built-in method (you can create a feature request here)
But this is an workaround to do it: http://jsfiddle.net/zcvq0yhh/5/

how to validate and add date using jquery

I am working on a health website.
I am having a field called Last Menstrual Period, its a textbox which has to be filled in by doctor in format of YYYY-MM-DD.
What I want to do is, I have to add 281 days into the LMP date that the doctor will be entering in order to generate the Expected Delivery Date (Child Birth)
So I need followings thing to do:
The date entered should be in format of YYYY-MM-DD
It should be a valid date i.e. taking care of leap years and invalid dates like 2013-02-31 etc.
After generating the Expected Date of delivery (based on LMP that is entered), it should be displayed on screen.
As soon as the date is entered in the LMP textbox, these validations should be performed and the Expected Date Of Delivery is displayed inside a tag below the LMP textbox
How can I do that? Here is what I have tried so far.
// Calculate Expected Date Of Delivery
$('#lmp_date').change(function()
{
var lmp_entered = $this.val();
if(lmp_entered)
{
// $('#edd').html('1');
}
else
{
// $('#edd').html('Please enter last menstrual date to calculate EDD');
Please help me how to implement these validations and display the date using jquery. I am a newbie in jquery so dont know much about it. Any small help will be highly appreciated.
for validation I don t recommend using another library especially for such a simple rule. if the rule is so strict just write your own and use it site wide.
For example block non-numberic entries to textbox and add dash "-" by your code in every 5th and 9th chars.
Then to validate check the length of text and dashed, use split to get year. month and day separately and convert it to date with Date(txtYear,txtMonth,txtDay) if your date's year, month and day are equals to your txtYear, Month and Day then it means it s a valid date. After that use the below to calculate birth date.
just use Date constructor like below
var delDate = new Date(year, month, day + 281)
Just don t forget months start 0 in JS so Jan = 0, Feb = 1 etc.

Javascript Date acting weird

Okay, I have heard about it but I can confirm now that the Javascript Date functionality is a disaster zone. And I have created a monster out of it. I have this Program :
A JSON object contains list of holiday dates and its respective label.
I need to find out the date of 5 business days from today (excluding saturday, sunday and holiday if any which is contained in the JSON object.) Good stuff so far. Then this 5 business days' date is going to be devoured by the jquery calender as a default selected date which is not included in the fiddle as it is irrelevant. (Note: the start date on the calender is tommorow's date) Good stuff again. THEN, comes this part: If it is before noon today, I can select tommorow else start date is day after tommorow. I'm elaborating this because it is included in this fiddle.
So the problem is multiple initialization of the function which handles above functionality is not producing consistent result. It was calculating 5 business days on my system, but when i made this fiddle, it is calculating 4. The date of "5th" business days is incremental by 1 on each call.
http://jsfiddle.net/xXQ7j/27/
Anyone!
Your problem is probably caused by timezone issues.
Whenever possible you should use new Date(y, m, d) to create a date object, rather than supplying a string. In particular, I've found that you get a date relative to 00:00 UTC if you specify a string in format yyyy-mm-dd but one relative to local midnight if you use yyyy/mm/dd.
In any event, I would suggest a different approach:
convert your holiday date into an object, with the date being the key
generate today's date
if it's after noon, get tomorrow's date - d.setDate(d.getDate() + 1)
create an empty array
add one day (per #3 above)
check if the new day is Saturday or Sunday, if so, go back to #5
check if the new day is in the holiday list, if so, go back to #5
add the new date to the array
repeat until you have 10 entries
That should give you the next 10 business days in your array. Pick the ones you need to fill out your date picker.

Categories