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.
Related
In case I have a Date and I want to check if the time is DST I can use a method, such as the following:
function isDST(d) {
let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
return Math.max(jan, jul) != d.getTimezoneOffset();
}
(source here)
In case I use MomentJS library I reach the same in this way:
moment().isDST();
Anyone knows how to do the same with the upcoming Temporal?
I'd recommend not doing this, at least not in this form.
Aside from the Ireland example mentioned in the comment, there are other time zone jurisdictions where there are one-time or non-semiannual changes in the offset from UTC that occurred for other reasons than DST, and any possible isDST() implementation will, by definition, malfunction in these cases. Another example is that Morocco observes year-round DST except during the month of Ramadan. For most of the world's population, "DST" has no meaning at all.
To solve this, I'd start by asking what you are going to use the information for?
If it's, for example, to specify "Daylight" or "Standard" time in the name of a time zone, you could instead use Intl.DateTimeFormat with the { timeZoneName: 'long' } option, which will give you the name of the time zone with this information included.
If you need it as a drop-in replacement for Moment's isDST() method so that you can port an existing system from Moment to Temporal, I'd recommend reimplementing the Moment function exactly, and plan to move away from the concept of "is DST" in the future. (Note, that the Moment documentation also describes this function as a hack that sometimes doesn't provide correct information.)
The body of the Moment function can be found here and the equivalent for Temporal would be:
function isDST(zdt) {
return (
zdt.offsetNanoseconds > zdt.with({ month: 1 }).offsetNanoseconds ||
zdt.offsetNanoseconds > zst.with({ month: 6 }).offsetNanoseconds
);
}
Another thing that you might need this information for is to interface with other systems that include an "is DST" bit in their data model (which is an incorrect concept, but you might have no choice.) In this case I'd recommend restricting the "is DST" function to a list of allowed time zones that are known to employ the concept of "DST" and returning false in other cases, which should at least filter out some of the false positives.
if (!listOfTimeZoneIDsWithDST.includes(zdt.timeZone.id))
return false;
the temporal api has a offsetNanoseconds read-only property
zdt = Temporal.ZonedDateTime.from('2020-11-01T01:30-07:00[America/Los_Angeles]');
zdt.offsetNanoseconds;
// => -25200000000000
also there's the with method which returns a new object with specified field being overwritten.
i have to admit i haven't tested it but something like this should basically be the equivalent to your function. (month index starts at 1)
function isDST(d) {
let jan = d.with({month: 1}).offsetNanoseconds ;
let jul = d.with({month: 7}).offsetNanoseconds ;
return Math.min(jan, jul) != d.offsetNanoseconds ;
}
zoned DateTime
refine dev
web dev simplified
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.
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.
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.
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".