Update value every month using Javascript - javascript

everyone!
I was looking for solution of this for a long time and didn't find anything.
I need to make element on page which will have +=2000 every month from ..let's say today's date.
And I am puzzled without any idea how to do this.
I easily wrote updating value every 10 seconds, but what about months that have different length and so on?
Should I compare difference between current date and today's date, than do +=2000*numberOfMonths? Then how often should I check if month has passed no to kill speedload?
Or is there any other convinient way to do it?
I know the solution might be easy, but I don't get it.
Will be gratefull for any suggestions.

You can do it like:
const getMonthsPassed = () => {
const startDate = new Date(2018, 10, 22); // month start at 0
const currentDate = new Date();
const monthDifference =
(currentDate.getFullYear() - startDate.getFullYear()) * 12 +
(currentDate.getMonth() - startDate.getMonth());
return monthDifference;
};

Related

How to format JavaScript Date object to not let hours overflow?

Let us consider following example
const date = new Date(0);
date.setSeconds(60*60*24-1);
console.log(date.toISOString().substr(11, 8));
outputs
23:59:59
I am searching for elegant way to have
const date = new Date(0);
date.setSeconds(60*60*24+1);
console.log(date.toISOString().substr(11, 8));
output
24:00:01
instead of
00:00:01
by elegant I mean without implementing my own Date object... Maybe it would be possible to set a custom length of the day? Increase from 24h to 99h?
You can set the hour cycle in the hour cycle option (hc) and the language parameter available in the Intl.DateTimeFormat constructor and toLocaleTimeString, e.g.
console.log(
new Date(2020,7,1,0,5).toLocaleTimeString('en-CA-u-hc-h24')
);
Whether the hour cycle setting "works" or not seems to depend on the language chosen and how it's set, so maybe not that reliable. Test thoroughly in different implementations.
Many thanks to #RobG who understood my question. The hour cycle is what I needed, unfortunately according to the docs it is restricted to values h11, h12, h23, h24 and I would need h99 which is not available.
Eventually I had to make my own ugly solution as it appears such a use case was not predicted in the standard, so here it is
function unfortunatelyWeHadToWriteIt(nbsec) {
// compute numerical values
const nbhours = Math.floor(nbsec/(60*60));
const nbminutes = Math.floor((nbsec - nbhours*60*60)/60)
const nbseconds = Math.floor(nbsec - nbhours*60*60 - nbminutes*60);
// convert them to padded strings
const hours = String(nbhours).padStart(2, '0');
const minutes = String(nbminutes).padStart(2, '0');
const seconds = String(nbseconds).padStart(2, '0');
// format
return `${hours}:${minutes}:${seconds}`;
}
so let's compare it to the Date formatting
// 27 hours, 13 minutes and 6 seconds
const nbsec = 60*60*27+13*60+6;
what Date will give us
const date = new Date(0);
date.setSeconds(nbsec);
console.log(date.toISOString().substr(11, 8));
outputs 03:13:06, it overflows at value of 24 hours. Now let's apply the unfortunatelyWeHadToWriteIt function
console.log(unfortunatelyWeHadToWriteIt(nbsec))
outputs 27:13:06 which does not overflow.
Just to give you guys some context, I am playing games and displaying the playtime. It is more convenient to show number of hours than number of days of gameplay...

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

How to add time to a date in js

I get a date with string type from API and then I parse it to a date type so that I can use it for a count down.
I want to add 30 days to the date that I've got from API.
Here is the code that I parsed
const time = Date.parse("2020-12-30T18:35:43");
I've already read this question and I tried to implement it
Add 10 seconds to a Date
but react does not recognize the getDate
if you need more information, please let me know
You need to wrap your parsed date with a new Date()
const time = new Date(Date.parse("2020-12-30T18:35:43"));
// As mention by other comments, this is enough
// const time = new Date("2020-12-30T18:35:43");
time.setSeconds(time.getSeconds() + 10) // 1609349753000
setSeconds and getSeconds are method of the Date, you was trying to execute them on a number.
EDIT :
Answer can be found here
In a general way you should use date-fns for date manipulations ;)
you can also setDate to your existing date. Check following code.
const date = new Date("2020-12-30T18:35:43");
date.setDate(date.getDate() + 30);

Need help subtracting time and date with Google SCRIPT

I have this code here:
var date = a.created_at_timestamp.substring(0,10)
var time = a.created_at_timestamp.substring(11,19)
And both these values return strings with these values:
date = 2020-05-19 //
Time = 17:00:08
I need to subtract 3 hours since it's coming in GMT time and I'm on GMT-3. Therefore, I thought about adding them together, subtracting three hours, and putting them apart again. Something like:
Orig Date: 20/05/19 //
Orig Time: 20:15:19
Time + Date: 20/05/19 20:15 //
Time + Date - 3h: 20/05/19 17:15
New Date: 20/05/19 00:00 //
New Time: 17:15:19
I tried converting it to milliseconds as suggested in other post here, doing with formulas, where a function would trigger formulas adding both cells, which I was able to do, but couldn't tear them apart together. In addition, if possible, I'd like to do it inside the script.
Can someone help me with that?
I'm new at this and I'm somewhat used to VBA. Tried some things from VBA, but they don't really apply here.
Instead of having separate strings for date and time, it'd likely be easier to just create a new Date object with both combined.
var dateTime = new Date(a.created_at_timestamp.substring(0,19));
You can then subtract 3 hours by doing:
var timeOffset = 3 * 60 * 60 * 1000; // 3hrs of millis
var offsetDate = new Date(dateTime.getTime() - timeOffset);

How do I convert current time to GMT?

I need to get the value of 00:00:00 AM GMT(12am) for the current day and then convert it to unix time. How would/should I go about doing that in javascript? Is there an outside data source that is more reliable then server time? I will be doing this in node on the server.
Thanks!
EDIT: This is what I did. Do you see any problems with this? Thanks again!
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Your method is right, but you have got a nasty bug in there, you are mixing local year with UTC date and month, for a few hours around new year, depending on time zone, the local and the UTC year is different, so if you use the wrong year your result will be a whole year off.
There are two interpretations of your question. Either you want a result based on the local time, so the result at any given time will depend on the time zone. Or you want a result based on UTC time that is the same no matter time zone, but sometimes for some users the result will not be the local date.
Local time:
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getMonth(),date.getDate()) / 1000
UTC:
date = new Date()
start_date = Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
This is a good place to start:
var now = new Date();
var then = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var epoch = then.getTime();
Not sure what you want to do about DST, so you'll need to look at:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
Edit: To allow for different timezones:
var off = now.getTimezoneOffset() * 60000; /* tz is in mins so multiply to ms */
var midnight = new Date(then.getTime() - off);
var epoch = midnight.getTime();
These links have some good answers. I love epochconverter.com it's saved me many hours of frustration. The essence of the answer is to use the Javascript Date object to handle all the nastiness of converting dates around. This is generally what you should do in any languages. If you are doing date manipulation by hand you will get it wrong.
http://www.epochconverter.com/programming/#javascript
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
This is what I ended up doing for anyone else looking at this question.
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Please let me know if you see any reason this wouldn't work.

Categories

Resources