Auto-populate field with date from another field + 14 days - javascript

Having searched endlessly for an answer, nothing has so far worked - so here I am hoping someone can assist.
I have 2 fields:
Action_Date & Deadline
The user updates the Action_Date field with the date they worked on the item. I then need to auto-populate the Deadline field with Action_Date + 14 days.
I have tried this so far:
function testCalc() {
var actionDate = new Date(document.getElementById("Action_Date").value);
var sla = 14;
var deadline = actionDate + sla;
document.getElementById("Deadline").value = deadline;
}
Action_Date calls this function via onblur()
The Deadline field auto-populates with the same date as Action_Date, in full format (e.g. Thu Jan 01 2015 00:00:00 GMT+0000(GMT Standard Time)14
Clearly the 14 days are not adding. Additionally I need Deadline to show the result in dd/mm/yy.
Any ideas most welcome!

Javascript dates are in milliseconds by default. So adding "14" to it is simply adding 14 milliseconds not 14 days. You will need to investigate more about Javascript Dates() here:
http://www.w3schools.com/jsref/jsref_obj_date.asp
Or use a framework of some kind like moments.js which is one of the best date handling frameworks out there. Date manipulation is one of the more complex things we developers have to do on the web due to issues with their local time, server time, etc.

Related

Get accurate week day name and time using JavaScript from internet not from local system

I'm a fresher Magento developer. I wanted to display and use current/accurate day and time in my website.
Currently I am using system time in the website based on which html div are being displayed, which is not right for further since every system date and time are not configured correctly.
I have tried using Google Timezone api, but I have no idea on how to use it. Although it is displaying the country name but how to extract weekday and time from that timezone using JavaScript.
Alright, you want the week-day: very simple. You can first fetch the entire string from the endpoint http://www.timeapi.org/gmt/now?\a%20\I:\M:\S. This will give you the current time in the form of <weekday> <time>.
For example: Tue 07:17:02. Now, the Indian Standard Time (IST) is GMT +05:30. So, let's extract the details and do some basic math:
// ... I am assuming that you've fetched the date using some request and it's not in the variable.
var dateGot = "Tue 07:17:02";
var weekDay = dateGot.split( ' ' )[0]; // Yeah! You can now use the week day.
// Now, you need to add 5 hours and 30 minutes to the second part of 'dateGot'.
// ... time adding routine
var addTime = function ( originalDate, hours, minutes ) { ... }
var currentTime = addTime( dateGot.split( ' ' )[1], 5, 30 );
// Now you can use 'weekDay' for the current weekday and 'currentTime' for the current time.
This API provides a service to get the date-time. A simple example is to wrap it up in jQuery AJAX calls, and then use it.
Example:
http://www.timeapi.org/utc/now?format=%25a%20%25b%20%25d%20%25I:%25M:%25S%20%25Z%20%25Y
Gives
Tue Nov 10 06:49:28 +00:00 2015
You can hack it according to your liking.
As per your wish, we can have it display only the weekday:
http://www.timeapi.org/utc/now?\a
which gives
Tue

DatePicker Error in Angular JS due to UTC

I have selected the 12th of September 2014 in the UI.
Following is the code
ctrl.$formatters.push(function (modelValue) {
console.log(modelValue);
var dt = new Date(modelValue);
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
console.log(dt)
return dt;
});
The two console logs i see are the following.
09/11/2014
Wed Sep 10 2014 18:30:00 GMT+0530 (IST)
Am not sure why the conversion from UTC to local is not carried out correctly.
Thanks in advance.
Its not clear what you are trying to do. The input does not have a time. Do you want to add the current time of the day to the arbitrary date? Or do you just want a local representation of the date? I'm geussing the latter.
Instead of dt.setMinutes(...) and the following two lines, replace all three lines with:
return dt.toLocaleDateString();
If you ARE trying to set the time to now on whatever date is input (I don't know why...) but you might try:
dt.setTime( new Date().getTime() );
instead of the setMinutes(...) line.
then you can
return dt.toLocaleString;
All date objects are stored as miliseconds since, like 1972. It is best to use the built in Date object methods to get what you want from it. Here are the docs for reference.

Angularjs, Datepicker one day beind

I understand that the datepicker (I'm using AngularStrap's datepicker) is "behind" a day because of how dates are calculated in javascript. My problem is, how to I get it to not take the timezone into consideration and just stick with the entered date... no adjustments?
I select February 1, 2014 in the datepicker. My value on the screen is 2/1/2014 and I want that value to be saved. However, the datepicker turns this into Fri Jan 31 2014 19:00:00 GMT-0500 (EST) apparently because it subtracts the 5 hours for my timezone from the entered date. I do not want this. If I enter 2/1/2014 I want that date, regardless of the timezone.
What is the best way to intercept/change/edit this value so that entering 2/1/2014 gives me exactly that date... no conversion for timezone? Should I modify the datepicker code itself (this seems like a bad idea)? Should I change the value myself prior to sending it to the backend by adding in some sort of offset? If so, how do you add time to a value that console displays as Fri Jan 31 2014 19:00:00 GMT-0500 (EST)?
I solved this problem with a custom directive https://gist.github.com/weberste/354a3f0a9ea58e0ea0de
It's for Angular Bootstrap datepicker but I guess it should work for AngularStrap datepicker as well since it only depends on the corresponding ngModel rather than the datepicker itself.
Essentially, I'm reformatting the value whenever a date is selected on the datepicker (this value, a yyyy-mm-dd formatted string, will be stored on the model) and whenever the model is accessed to populate the view, I need to wrap it in a Date object again so datepicker handles it properly.
In other words, it is exactly doing the interceptions that you ask for in your question.
I know this thread is kind of old but since there is no accepted solution I thought I'd offer what finally worked for me after lots of messing around:
The issue in my case was that the datepicker was using the wrong timezone so when I would try to edit an event, the wrong date would display even though the correct date was stored in the db. The following fixed it for me:
var evDate = new Date(data.eventDate); //data.eventDate is the date string
evDate.setMinutes(evDate.getMinutes() + evDate.getTimezoneOffset());
$scope.eventInfo.eventDate = evDate;
I found this solution here: https://github.com/angular-ui/bootstrap/issues/2628
If you don't mind loading another resource, then I would recommend using MomentJS as it takes the pain out of dates in JavaScript. You can do something like `moment(datepicker value).local()' to get the date without the timezone offset.
http://momentjs.com/docs/#/manipulating/local/
I have found a way. convert that date to string first. here is the code.
var SelectDate = $scope.GetFormattedDate(Date.parse($("#Date").datepicker("getDate")));
$scope.GetFormattedDate = function (CalDate) {
var re = /-?\d+/;
var WDate = CalDate.toString();
var m = re.exec(WDate);
var lastDate = new Date(parseInt(m[0]));
var mm = lastDate.getMonth() + 1;
var dd = lastDate.getDate();
var yyyy = lastDate.getFullYear();
var formattedDate = mm + '/' + dd + '/' + yyyy;
return formattedDate;
}
Now Pass SelectDate to your controller. bingo problem has been resolved :)
Guys if you are experiencing this problem is because probably,you are reactivily ,puting data in boostrap datepicker.This solution worked for me.
First you check if date is null
dateBegin===null?dateBegin=null:dateBegin = new Date(formatDate(dateBegin,'yyyy-MM-dd','en'));
**if is null you set its value to null which you are going putt in your Form Group and in Form Group Control
this.ugovorForm = new FormGroup({'dateBegin':new FormControl(dateBegin)})
else you will set Date and format it using formatDate property , provided by Angular.I was struguling with this problem for along time.And its because I'm loading dates from Database.Good Luck;

why javascript's .getTime() + 24*60*60*1000 get's stack after 27 Oct 2013?

I was just creating a simple calendar when users clicks next it gets the following day, very simple code:
var dateSelected = new Date('02/06/2013'); //any date
var day = new Date(dateSelected.getTime() + 24*60*60*1000);
alert(day.getDate());
that works great for all dates but for some reason it doesn't get the next day when the date is 27 Oct 2013
var dateSelected = new Date('10/27/2013');
I don't seem to be able to figure out why, if I go manually to the next day 28 Oct it keeps working fine.
Any ideas why this happens?
UPDATE:
I fixed it by adding the time as well as the date:
var dateSelected = new Date('10/27/2013 12:00:00');
I strongly suspect this is because of your time zone - which we don't know, unfortunately.
On October 27th 2013, many time zones "fall back" an hour - which means the day is effectively 25 hours long. Thus, adding 24 hours to your original value doesn't change day if it started within the first hour of the day.
Fundamentally, you need to work out whether you're actually trying to add a day or add 24 hours - they're not the same thing. You also need to work out which time zone you're interested in. Unfortunately I don't know much about Javascripts date/time API, but this is almost certainly the cause of the problem.
Rather than adding the number of milliseconds in a day, you can use the set date function directly.
var dateSelected = new Date('10/27/2013');
var daysToAdd = 1;
var nextDay = new Date(dateSelected.getTime());
nextDay.setDate(dateSelected.getDate() + daysToAdd);
This also works when rolling over to the next month, and should work well with different time zones.
As Jon Skeet already mentioned, the problem results from your local timezone. As a possible solution, you can use the setDate and getDate functions of the Date object:
var dateSelected = new Date('02/06/2013'); //any date
dateSelected.setDate(dateSelected.getDate() + 1);
alert(dateSelected.getDate());
And of course, no JavaScript Date question could be complete without a Moment.js answer:
var m = moment('10/27/2013','MM/DD/YYYY').add('days', 1);
Superior API every time. :-)

Javascript: Why a date does not return the right day?

I'm from Brazil and I've written this piece of code in Javascript
var dt = new Date(2012,9,21); // Oct-21-2012
alert(dt.getDate());
However, it produces 20 and not 21. I've tested with Firefox 18, Chrome 24 and Internet Explorer 8.
How it is possible?
You came across a huge coincidence.
In Brazil, Oct-21-2012 is the start of daylight saving time in most of the country, so local dates at Oct-21-2012 between 0:0 and 1:0 doesn't exist in Brazil!
Some people from other countries did not face the same problem in the same date.
See: http://www.timeanddate.com/news/time/brazil-dst-2012.html
In Brazil the code inside the question really outputs 20
var dt = new Date(2012,9,21); // 21-Oct-2012 0:0
alert(dt.getDate());
However, a slight change generates 21, because 1 hour is enough to "jump over" the lost hour:
var dt = new Date(2012,9,21,1); // 21-Oct-2012 1:00
alert(dt.getDate());
See: http://www.timeanddate.com/time/dst/2013.html
Edit after comments: In United States, for instance, at 10 March, 2013 will start the daylight saving time.
var dt = new Date(2013,02,10); // March-10-2013
alert(dt.getDate()); // Output: 10
Why it is right? Because in the USA the daylight saving time jumps at 2:00 and not 0:00 like in Brazil, therefore implicit 0 hour protect the generated date against problems.However, it is still possible errors in hours elapsing calculation.
-/-
In Brazil the situation should to induce a bug in many sites that handle with dates, regardless of time. One can enter a date in a form and the algorithm calculating elapsed days in a wrong way.
For instance, if somebody uses this nice javascript code to enter dates in a form (
DHML Goodies Calendar ), and after one decides to save that date in a database, it is possible that one get the wrong date, if one has a bad luck to meet special dates.
The definitive solution is use UTC (Coordinated Universal Time) time, because there is no Daylight Saving changes and you use a kind of abstract time. In most practical applications there is no problem.
var dt = new Date( Date.UTC(2012, 9, 21, 8, 5, 12));
alert( (dt.getUTCMonth()+1) + '/' + dt.getUTCDate() + '/' +
dt.getUTCFullYear() + " " + dt.getUTCHours()+ ':' +
dt.getUTCMinutes() + ':' + dt.getUTCSeconds() );
Instead of using UTC, it is easier, if someone doesn't use hours, minutes and seconds, just put a dummy hour value greater or equal than 1, as I have shown above, in Date() call.
Edit after comments: So the Brazil (and countries like Iran,Lebanon, Paraguay, Chile and Portugal ) should change the start of daylight saving time to 2:00 and not 0:00, in order to avoid this confusion and get aligned to more developed countries.
-/-

Categories