Google Apps Script get current month from Date() - javascript

I'm currently working on a function to generate data according to a start and an end date.
While I was testing my functions I've realized some wrong calculated values.
Long story short the getMonth() method for Date objects is returning a unexpected value.
var date = new Date();
console.log(date.getMonth());
var date2 = new Date(2014, 1, 1);
console.log(date2);
Can someone explain to me the reason why to start a month at 0, even if it's not possible to create a right Date object using that index.
Even though date2 my second example is from the official docu of JS and is returning a unexpected value according to the example giving in the "Parameters" section.

As #Airwavezx mentioned the code was correct.
tl;tr I forgot to use timezones and JS is counting months from 0
So a solution to my question could be:
var date = new Date();
console.log(date.getMonth()+1);
var date2 = new Date("2014-01-01T00:00:00Z");
console.log(date2);

Related

How to compare dates without including the hour

So there is a column that has the date with the hour and i was trying to create a variable date with the same date, month, year and hour to be able to compare it wiht that date but this didn't work with me so I thought I would do that by creating the same date but when i compare i won't consider the hour but im facing some difficulties.
anyone of the two solutions would be great
I wrote many other codes but none of them worked and that was the last one i wrote
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var date = month+'/'+day+'/'+year;
Logger.log(date);
Im using JavaScript in google app script.
Thank you!
From MDN
We have a first step to create an object date.
let today = new Date()
let birthday = new Date('December 17, 1995 03:24:00')
let birthday = new Date('1995-12-17T03:24:00')
let birthday = new Date(1995, 11, 17) // the month is 0-indexed
let birthday = new Date(1995, 11, 17, 3, 24, 0)
let birthday = new Date(628021800000) // passing epoch timestamp
You can create your Date object following the example above that fits you better. I also recommend giving a good look into this page.
For the second step...
From there, you can use Date.now(). As explained here, this will return "A Number representing the milliseconds elapsed since the UNIX epoch."
The third step is...
comparing both numbers. Which one is smaller will be an "earlier date" and vice-versa.
If some dates don't have time, I would consider it as midnight. Using the default Date format, that would be something like this.
yyyy-mm-ddThh:mm:ssZ
Ex:
2022-02-21T09:39:23Z
The Z at the end means UTC+0.
More about this on this link.
So, a date without time would be:
2022-02-21T00:00:00Z

Get all the months and year from provided ISO Date to current month and year

Suppose I have ISO Date inside an object as:
const dataCreated = {"readDetail":'2020-09-17 14:23:26.978Z'}
Is it possible to I get all date from created date till todays date.
Expected O/P ->assunming current date is jan 2021 :
['2020-09-17','2020-10-17','2020-11-17','2020-12-17','2021-01-17']
I tried different searches but was unable to get find anything related to it. If anyone has any solution or in someway can guide me that would be really helpful. If any further information needed please let me know.
What you want to do is just fill your array while looping over the dates. And with each loop add one month to your original date.
Note that you have to to create a new Instance of Date before saving it in your array since JavaScript saves references.
function getDates() {
var date = new Date("2020-09-17 14:23:26.978Z");
var now = new Date();
var datearray = [new Date(date)];
while(date.setMonth(date.getMonth() + 1) < now) {
datearray.push(new Date(date));
}
console.log(datearray);
}
Contrary to your expected output I'm saving Date Objects in the array. This has the advantage of giving you more opportunities when working with the Array elements afterwards. This could easily be changed though by changing the line where the Date object is pushed to the array.

Date restrictions on user input in JavaScript

I am trying to have a date entry box which has the following restrictions. Date must be today's date or earlier, but not more than 1 year previous. I have the following line:
if (myFDGDT - todayDate > 0 || (myFDGDT - todayDate)/86400000 < -365)
The first portion of that creates the appropriate alert when some enters a date after today's date. Not sure about the best way to cap the entry to a year previous. Attempted a few items, but the above was just an example of my last attempt. This is also written in a dependency and not in the Global JavaScript of our entry client.
Here is a snippet that will generate a Date object that is one year ago. You can compare against it as needed using greater than/less than operators.
var oneyear = new Date('01/01/1971'); // from unix epoch
var now = new Date();
var oneyearago = new Date(now - oneyear);
alert(oneyearago);
If you are manipulating dates a lot in your app you should consider using the momentjs library. For your problem the solution would be something like:
var momentdate = moment(date);
if (momentdate.isAfter(momentdate.add(1, 'year') ||
momentdate.isBefore(momentdate.startOf('day')) {
// Invalid date?
}
Hope this helps.

setHours() convert my Date object in string timestamp

I try to set a date to midnight to simplify my date manipulation, for this I wrote this part of code:
var now = new Date();
today = now.setHours(0,0,0,0);
console.log(now, today);
I'm surprised to see now contains a Date object and today a timestamp. This brings errors when I want to use getMonth() or other date's functions. It's paintful to recreate a Date object with the timestamp.
Is it normal? How can I fix this?
(Feel free to update my post to correct my bad english :)
Is it normal?
Yes
How can I fix this?
You are assigning the return value of now.setHours(0,0,0,0)to today.
Maybe what you are looking for is something like this:
var now = new Date();
var today = new Date();
today.setHours(0,0,0,0);
In this way, setHours is acting upon the value you wish to have the hours set on. This is the primary manner of using setHours.
Other details
The specification doesn't appear to mention the return value. Other sites such as w3schools do.
The Chromium setHours source shows a value being return though other functions that perform similarly do not return this value. I presume that the SET_LOCAL_DATE_VALUE function found in chromium's date.js is assigning the value into the first argument.
I had a similar situation and pcnate answer didn't solved my issue...
What I did was:
var today = new Date();
today = new Date(today.setHours(0,0,0,0));
console.log('Date: '+today);
You can manipulate dates easily using datejs or momentjs
date.js:
Date.today().set({ hour : 0 });
moment.js
moment().set({ "hour": 0, "minute" : 0, "second": 0});

Date to epoch and vice versa - JavaScript

I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

Categories

Resources