Is the IF function removing the date object in javascript? - javascript

I've spent an hour looking for answers and trying different things so I appreciate any help here.
The following code works great for finding someone's part B effective date. However, when someone's birthday is really on the 1st of a month the 'if' function get's used, and I'm no longer able to format and write the date. It's almost like 'partB_eff' is no longer a date object. (I'm a newbie, so I might just be making this part up.)
I'm getting the error "TypeError: partB_eff.toLocaleDateString is not a function at AutoFill_6_Step_Checklist(Code:24:27)"
How can I resolve this?
let birthday = new Date(e.values[2]);
//this is a date entered from a google form
let bdayCopy = new Date(birthday);
//I created this since I'll be using .setMonth(), and I don't want to change the original date of the birhtday
let bday65 = new Date(bdayCopy.setMonth(bdayCopy.getMonth()+780));
//finds the 65th birthday
let partB_eff = new Date(bdayCopy.setDate(01));
//find's the Medicare part B effective date (the 1st of the month someone turns 65)
if(birthday.getDate()==1){
partB_eff = partB_eff.getMonth-1;
//if the person's birthday is really on the 1st of the month, the part b effective date is the 1st of the month prior. partB_eff must be converted
}
partB_eff = partB_eff.toLocaleDateString('en-us',{year:"numeric",month: "short",day:"numeric"});
//format partB_eff so that it looks nice on paper

partB_eff = partB_eff.getMonth-1;
Doesn't do what you think it does. What it does is get the vound function getDate from your date object, and attempt to subtract one from it. In any other language trying to do subtraction on a function would be a type error, but Javascript is Javascript and allows numeric operations on almost any type. A function minus a number in JS is NaN. NaN doesn't have a method called toLocaleString, hence the error.
What's interesting is that you did the same operation correctly above with bdayCopy.setMonth(bdayCopy.getMonth()+780)
Just do the same thing here
bdayCopy = new Date(bdayCopy.setMonth(bdayCopy.getMonth()-1));
Also some important concepts. if in Javascript is not a function. if is a keyword that starts a conditional statement. You can't do any of the things you can do with a function with if. You can't call it or assign it to a variable or pass ot as a function argument. Clearly understanding what a function is is something you need to do to be able to work in JS, or frankly any other language.
Finally if you are doing date math in JS I strongly recommend you use a date library like DateFns or Moment. Javascript native date APIs are possibly the worst designed date API of any language ever.

Related

Formatting String to Date in JS

I'm sure this is a simple question, but I can't for the life of me solve it.
I have a JSON object as so:
{
"_id": {
"$oid": "57cb5aac9bd9a31100c793d1"
},
"reminders": [
"2014-03-12T12:00:00",
"2014-03-12T13:37:27",
"2014-03-12T13:37:27",
"2014-03-12T22:14:27"
],
"user": "xxx"
}
I want to parse the date from the reminders is JS to a date object in a loop, as so.
for (var i = userSchedule.reminders.length - 1; i >= userSchedule.reminders.length - 1; i++)
{
var date = new Date(userSchedule.reminders[i]);
}
But it just displays invalid date whenever I log it. Any ideas?
Though its not answer but why have you used user_schedule.reminders and userSchedule.reminders and your for loop will loop only once with correct data since your loop begins with i=3; which is index for last element of userSchedule.reminders[3] and when you loop next it will go beyond the scope of your array reminders
Something here is not as it seems, because calling the date constructor in both Chrome and Node.JS returns the correct date for me. I also tried it in the JSBin below.
https://jsbin.com/fomagugiwe/edit?html,output
I would log the value going into the date constructor, just to ensure that the value being used is of the correct format. Could you also provide the Node version you are using for this script for further testing..
for date time manipulation I strongly recommend using http://momentjs.com
where you can do
moment("your date string")
Or
moment("your date string","your date format")
Your loop is broken, it seems you're trying to iterate from 0 to userSchedule.reminders.length - 1, so:
for (var i=0; i < userSchedule.reminders.length; i++) {
// do stuff
}
Also, parsing date strings with the Date constructor (and Date.parse, they are equivalent for parsing) is not recommended due to variances in implementations. You should parse the string manually, a library can help but isn't necessary if you have only one format to parse.
A date string like "2014-03-12T12:00:00" should be treated as "local" (i.e. the host time zone offset should be used when calculating the time value), however not all implementations will do that. A small library like fecha.js makes it simple:
var d = fecha.parse('2014-03-12T12:00:00','YYYY-MM-DDTHH-mm-ss');
You can also use moment.js, but it's likely overkill for what you need. There are many other parsing and formatting libraries available that are suitable too.

How do i use a for loop to loop every argument into newDate?

I have a timeMachine function that takes in 5 parameters and tells you what day it is after the time you entered. But instead of writing newDate.setDate(dateObject.getDate()+daysLater); i want to use a for loop that loops over the arguments' length and logs the inputs into newDate.
var timeMachine=function(yearsLater,monthsLater,daysLater,hoursLater,minutesLater) {
var dateObject=new Date();
var newDate=new Date();
newDate.setDate(dateObject.getDate()+daysLater);
newDate.setMonth(dateObject.getMonth()+monthsLater);
newDate.setYear(dateObject.getFullYear()+yearsLater);
newDate.setHours(dateObject.getHours()+hoursLater);
newDate.setMinutes(dateObject.getMinutes()+minutesLater);
console.log(newDate);
}
timeMachine()
This isn't using a for loop, but I'd suggest using MomentJS for any date-based manipulation. Speaking from personal experience, time manipulation is easy to mess up.
Moment already has this sort of "timeMachine()" functionality built in. For instance:
var futureMoment = moment()
.add(yearsLater, 'years')
.add(monthsLater, 'months')
.add(daysLater, 'days')
.add(hoursLater, 'hours')
.add(minutesLater, 'minutes');
console.log(futureMoment.format()); // <<== get a formatted string
console.log(futureMoment.toDate()); // <<== 'toDate' gets the native Date object
It also has copious documentation, and good plugins for added functionality. If you add moment-parseformat, you can easily parse most real-world Date strings (i.e. "November 20th, 2015" or "11/20/15" or "2015/11/20", etc) into Moment objects.
Basically, don't do this yourself unless you really need the bare bones functionality. Standing on the shoulders of giants is much easier.

Dates - JavaScript and C#

I hate dates, I can never get them to behave.
I have a javascript variable that looks like this:
var currentDate = new Date();
I pass this to a C# Web API controller as a parameter.
My local time was 12:43 but when I put a breakpoint in my action it shows 11:43. The problem is, that if I do this at 00:43 then my controller would take the date as yesterday. I need it to pick out the right day. If I select the currentDate as 02/09/2015 12:43 then I need my controller to use the same date.
I know this has something to do with local times etc, but how can I get them all to use the same one?
Any help would be greatly appreciated.

Save the actual date in a variable (only date, no time)

I want to save the actual date in a variable. only the date, no time
var a = #Date(#Now());
datasource.replaceItemValue("variable", a)`
And
var a = #Date(#Now());
var b = new Date(a.getYear(), a.getMonth(), a.getDay());
datasource.replaceItemValue("variable", b)
Are returning 28.10.14 00:00
var dt:NotesDateTime = #Date(#Now());
datasource.replaceItemValue("variable", dt.getDateOnly());
Is throwing me an error
Isn't there a simple way to get only the actual date without the time?
Use setAnyTime() metohd of NotesDateTime class to remove time component.
If you want to save only the date use a textfield and convert the text to date, if you need it in your code
#Now uses a java.util.Date, which includes time portions. .getDateOnly() is probably throwing an error because that returns a String.
The underlying session.createDateTime() method accepts either text, a java.util.Date or a java.util.Calendar. I think all of them need to include a time element.
If you're only storing the value for reference, I'd agree with brso05 to not worry.
If you're ever likely to use #Adjust (or an equivalent), then not worrying about the time is a recipe for disaster, because every time you try to adjust, you need to remember to take into account Daylight Savings Time.
One option is to set the time to 12:00 midday. That means DST will not be a problem.
java.sql.Date is specifically designed to only include the Date portion, without a time element. Jesse Gallagher talks about java.sql.Date in the context of his frostillic.us framework https://frostillic.us/f.nsf/posts/32A63DD640D868D885257D18006659A9 and he was the one I found out about java.sql.Date from. I'm not sure how he stores those values though.
I'm not sure if the OpenNTF Domino API will allow you to just pass a java.sql.Date to a field and so store just the date portion.

Generating a unique ID in javascript. Understanding this code

Here is a code snippet i've come across for creating uniqueIDs in a script.
var now = (new Date()).valueOf();
var future = (new Date()).valueOf();
while(future == now){
future = (new Date()).valueOf();
}
return future;
My question is, why use .valueOf() instead of .getTime() and is the purpose of two date objects and a while loop to avoid the change of returning the same values if called multiple times. Surely the chances of returning the same millisecond representation of the date are slim to none? Any thoughts?
As you stated, the chance of getting back the same uuid is small - but not impossible. There is no real need to use valueOf instead of getTime. Also there are way better algorithms for generating UUIDS see https://github.com/pnegri/uuid-js for well tested implementations which are also time based.
I would personally use .getTime() method adding some kind of basic operation, such a pseudo-aleatory number generation added to the returned quantity in milliseconds. Simply because a millisecond is not 100% a reliable output, as Dan Pichelman said, "You'd be surprised how much you can do in a millisecond these days".

Categories

Resources