I have a curTime variable that is the current time using new Date() and a pwChangeDate value called from the backend data.
let curTime = new Date(); // Thu Oct 27 2022 15:02:34 GMT+0900
const pwDate = new Date(pwChangeDate) // Thu Oct 20 2022 13:51:57 GMT+0900
At this time, when pwDate passes 90 days based on curTime, I want to display an alert saying "90 days have passed." and when 83 days have passed, "7 days left out of 90 days." I want to display an alert.
but if i use my code it doesn't work how can i fix it?
const pwChangeDate = cookie.get('pwChangeDate');
const pwDate = new Date(pwChangeDate)
if (curTime.getDate() >= pwDate.getDate() - 90) {
alert('90 days have passed.')
}
if (curTime.getDate() >= pwDate.getDate() - 7) {
alert('7 days left out of 90 days..')
}
you can get the diff between current data and pwDate in days like this:
const pwDate = new Date('Thu Oct 20 2022 13:51:57 GMT+0900');
const diff = Math.floor((new Date - pwDate)/1000/60/60/24);
console.log(diff)
If you want to calcuate the days difference between pwDate and curTime, you can calculate like this.
Math.floor((pwDate.getTime() - curTime.getTime()) / (1000 * 60 * 60 * 24));
getTime() method returns a time value as milliseconds.
1000 * 60 * 60 * 24 is milliseconds per day.
OR
Using some library. (date-and-time)
Related
I am getting the elapsed time in minutes, hours and days, between two dates, a past date and the current one, I already get this data, but I want this data to change as the minutes, days and hours increase. For example, when I get to 60 minutes, the time changes to 1 hour and the minutes go to 0, when 24 hours go by, these hours change to a day and the hours go back to 0, and so on, the data I get keeps increasing , how can I do this?
const calculateDate = () => {
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const minutes= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60);
const hours= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / (3600));
const days= Math.floor((currentDate.getTime() - date.getTime()) / (1000*60*60*24));
}
With this, get the minutes, hours and days, but how would you update so that when you reach 60 minutes it goes to one hour and 24 hours to one day?
The JavaScript Date object has built in functions for what you want to do.
var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()
The new Date created in above example is set to the time it was created.
You can get the current time using the Date object itself:
var current = Date()
With your method you always see the full duration just in a different unit.
You have to use the modulo operator to get only the "missing part" (the remainder of the division) to the next unit:
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const dateDiff = (currentDate.getTime() - date.getTime()) / 1000;
const seconds = Math.floor(dateDiff) % 60;
const minutes = Math.floor(dateDiff / 60) % 60;
const hours = Math.floor(dateDiff / (60 * 60)) % 24;
const days = Math.floor(dateDiff / (60 * 60 * 24));
I'm trying to write a script to subtract 5 days from a defined date but seems not working, here's my code:
var End_Day = sheet.getRange(i + 2, 20).getValue();
Logger.log(End_Day);
var End_day_2 = new Date();
End_day_2.setDate(End_Day.getDate()-5);
Logger.log(End_day_2);
and the result is not just - 5 days:
11:18:47 AM Info Sat Jun 04 00:00:00 GMT+08:00 2022
11:18:47 AM Info Fri Apr 29 11:18:47 GMT+08:00 2022
I am quite confused why the date move from Jun to Apr.
Thanks for having a look
Try:
var End_Day = sheet.getRange(i + 2, 20).getValue();
var End_day_2 = new Date(End_Day.getTime() - (5 * (1000 * 60 * 60 * 24)))
Logger.log(End_Day);
Logger.log(End_day_2);
Function:
const endDay = sheet.getRange(i + 2, 20).getValue()
const endDay2 = DateFromDaysAgo(endDay, 5)
...
function DateFromDaysAgo(startDate, number) {
if (typeof startDate === `string`) { startDate = new Date(startDate) }
return new Date(startDate.getTime() - (number * (1000 * 60 * 60 * 24)))
}
You should learn more about Date.prototype.setDate().It only changes the day of the month of a given Date instance.
As the code you posted, the day of the month of End_Day is 4, End_day_2.setDate(4 - 5) equals to End_day_2.setDate(-1) and the month of End_day_2 is April according to the console result, because there're 30 days in April, setDate(-1) means setDate(29), so you got Apr 29 at the end. That's how it goes.
One right way to do is substracting 5 days worth of milliseconds.
function addDays(date, days){
const DAY_IN_MILLISECONDS = 24 * 60 * 60000;
return new Date(date.getTime() + days * DAY_IN_MILLISECONDS);
}
console.log(addDays(new Date(), -5).toString()); // 5 days ago
I am quite confused why the date move from Jun to Apr.
It's because you're setting date on today(End_day_2) and not on your predefined date(End_day).
Change
End_day_2.setDate(End_Day.getDate()-5);
to
End_Day.setDate(End_Day.getDate()-5);
console.info(End_Day);
If what's coming from the sheet is a string, you will have to convert the date string into a date object.
The other thing is you have to work in milliseconds as #vanowm says:
606024*5 = 432000 * 1000 = 432000000
so skipping the sheet entirely:
x = new Date
> Fri May 27 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
y = new Date(x - 432000000)
> Sun May 22 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
This will do the trick. Works with any date and can subtract any number of days
const subtractDays = (fromDate, numDays) => {
if (!(fromDate instanceof Date)) throw 'The first argument must be a date';
return new Date(new Date().setDate(fromDate.getDate() - +numDays));
};
Weekago
function weekago() {
let dt = new Date();
dt.setDate(dt.getDate()-7);
Logger.log(dt);
return dt;
}
Five days ago
function fiveago() {
let dt = new Date();
dt.setDate(dt.getDate()-5)
Logger.log(dt);
return dt;
}
Five days from a date in a spreadsheet cell
function fivefromadateinspreadsheet() {
const v = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
let dt = new Date(v);
dt.setDate(dt.getDate()-5);//Note that does not return a date it return the numbrer of milliseconds
Logger.log(dt);
return dt;
}
You can subtract 5 days from a defined date in Google App Script by using the Utilities.formatDate() method. Here's an example:
function subtractDays() {
var date = new Date();
var subtractDays = 5;
// Subtract 5 days from the current date
date.setDate(date.getDate() - subtractDays);
// Format the new date
var newDate = Utilities.formatDate(date, "UTC", "yyyy-MM-dd");
Logger.log(newDate);
}
In this example, we first create a Date object to represent the current date. Then, we subtract 5 days from the current date by using the setDate() method. Finally, we format the new date using the Utilities.formatDate() method and log it to the console using the Logger.log() method.
You can modify the subtractDays variable to subtract a different number of days from the date, or you can use a different date object to start with.
Is there a built in method in extjs or javascript for converting milliseconds to a time?
I found one for date, but it doesn't work. I always get Jan, 1 1970 08:00 (Pacific Standard Time). When I try test.getHours I get 0. I am trying to print out 8:00 or 08:00
var getSignOnRecord = 28800000;
var test = new Date(getSignOnRecord);
test.getHours() // 0 ???? Should be 8
you can use ISOString date formats for up to 24 hours of time:
new Date(28800000).toISOString().split("T")[1].split(".")[0]; // == "08:00:00"
you can easily slice() the remaining text to eliminate seconds or whatnot.
this works because using a "unix" stamp results in an GMT offset, and ISO also displays GMT, so by throwing away the date part, you're left with a pretty readable format of up to 23h59m59s...
You are getting the localized hour, but you want the hours at UTC
new Date(28800000).getUTCHours() // 8
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
The getHours() method returns the hour for the specified date, according to local time.
new Date(value);
value: Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC
28800000 ms is indeed 1 January 1970, 8h
When I try test.getHours I get 0
NB value is UTC, getHours is local time
This is a math problem. As far as I know, there is no function that does this in native JavaScript, but can be coded from scratch.
function convertToTime(milliseconds) {
var seconds = Math.floor(milliseconds / 1000) % 60
var minutes = Math.floor(milliseconds / (1000 * 60)) % 60
var hours = Math.floor(milliseconds / (1000 * 60 * 60)) % 24
return (hours < 10 ? "0" + hours : hours) + ":" +
(minutes < 10 ? "0" + minutes : minutes) + ":" +
(seconds < 10 ? "0" + seconds :seconds);
}
There's also probably a method like this in momentjs.
I am in a situation where I need to find out the total hour difference between two date objects but the thing is dates aren't present in the actual format.
Date 1: 6 Apr, 2015 14:45
Date 2: 7 May, 2015 02:45
If it would have been in standard format, simply I would have been used below method:
var hours = Math.abs(date1 - date2) / 36e5;
I am not sure how do I get the hour difference here... please help.
You can create date objects out of your strings:
const dateOne = "6 Apr, 2015 14:45";
const dateTwo = "7 May, 2015 02:45";
const dateOneObj = new Date(dateOne);
const dateTwoObj = new Date(dateTwo);
const milliseconds = Math.abs(dateTwoObj - dateOneObj);
const hours = milliseconds / 36e5;
console.log(hours);
You can create two date objects from the strings you have provided
var date1 = new Date("6 Apr, 2015 14:45");
var date2 = new Date("7 May, 2015 02:45");
then you can simply get the timestamp of the two dates and find the difference
var difference = Math.abs(date1.getTime() - date2.getTime());
Now to convert that to hours simply convert it first to seconds (by dividing by 1000 because the result is in milliseconds), then divid it by 3600 (to convert it from seconds to hours)
var hourDifference = difference / 1000 / 3600;
var date1 = new Date("6 Apr, 2015 14:45").getTime() / 1000;
var date2 = new Date("7 May, 2015 02:45").getTime() / 1000;
var difference = (date2 - date1)/60/60;
console.log(difference); //732 hours or 30.5 days
I'm not sure what you mean, but this works for me.
<!DOCTYPE html>
<html>
<body>
<p id="hours"></p>
<script>
var d1 = new Date("1 May, 2015 14:45");
var d2 = new Date("29 April, 2015 14:45");
var hours = (d1-d2)/36e5;
document.getElementById("hours").innerHTML = hours;
</script>
</body>
</html>
I have this script working it gives me the UTC time but it goes over 24!
example
sydney time 13 + (-11) = 2 | Los Angeles time 19 +(7) = 26
this 26 show be 2! because 24 is maximum
var now = new Date();
var utc = (now.getHours() + (now.getTimezoneOffset() / 60));
Use
now.getUTCHours()
For reference see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours
You don't need to, and shouldn't, calculate this. getUTCHours gets you UTC time.
That said, if you still want to do the calculation / make your life harder:
var now = new Date();
var utc = (now.getHours() + (now.getTimezoneOffset() / 60)) % 24;
The % 24 is necessary to account for situations (like you encountered) where the conversion yields a number outside 0-23.