I would like to restrict some actions if date is on sunday - e.g. do not allow create item on Sunday.
I use:
public isSunday(date: Date): boolean {
return date.getDay() === 0;
}
My problem is that my UTC offset is UTC+2.
Server and database runs on UTC TZ to prevent unwanted date and time shifts.
When I send datetime from frontend I use date.toISOString(), so my local datetime
2022-05-16 00:00:00 is converted to string 2022-05-15T22:00:00:000Z
When I check this date on the backend side, this date IS sunday, but in the UTC zone, not my local zone.
String value is converted to Date at the backend using following
new Date(input);
Edit: Value 2022-05-16T01:41:00+02:00 (sending value with utc offset info) does not work either
To my understanding, you need the local (UTC+2) zone on the back-end for only Sunday checks.
You can simply subtract 2 hours equal to milliseconds from the date received on the backend before the Sunday checks.
// ... get date here
date -= (2 * 60 * 60 * 1000); // subtract 2 hours
I don't think this is a good practice as your frontend may change its timezone but you can try this.
const date = new Date("2022-05-16 00:00:00")
const corrected_date = new Date(date.valueOf() - 7200000) //subtract milliseconds as needed, in this case 2*60*60*1000
console.log(corrected_date.getDay())
If possible, then you should maybe try sending the UTC offset as a seperate parameter to the backend and calculate the correct value to be subtracted for it to work dynamically.
Related
I'm attempting to output all days within the current week. e.g. for this week, show all days, 05/12/2019 through 05/18/2019 only. when the bot is executed next week, only show days 05/19/2019 through 05/25/2019. My current logic outputs the days for this week, but come tomorrow, the dates for this week will be thrown off. Please see the following
...could I get some help with this please?
Using VBS
I would do this using a VBS script, using Run Script command.
The default week start is Sunday you can change it check: https://www.w3schools.com/asp/func_weekday.asp
Pass the day you that you want as a parameter from 0 to 6, and get the data as a return value.
DayNumber: 0 = Sunday ..... 6 = Saturday
InputDate = Date
DayNumber = WScript.Arguments.Item(0)
Result = DateAdd("d", DayNumber - WeekDay(InputDate, 2), InputDate)
WScript.StdOut.Write(Result)
'MsgBox(Result)
Using MetaBot
Metabot Link: Change Date and Time Format
You will have to run the following logic in sequence.
Input: DayNumber: 0 = Sunday ..... 6 = Saturday
Using DayOfWeek Logic, Get the Day of the week and assign it to
WeekDay variable, it will return the name, not the number, and the input will be Date.
Using IF conditions convert the name of
the day to number, start from 0 to 6 as your first day in the week,
which is Sunday, and using variable operation assigns the value to
NumWeekDay variable.
Using variable operation, Get the offset by subtracting DayNumber, the day you want minus NumWeekDay,
and assign the value to Offset variable.
Using AddDays, Input
the date and the offset, and you will get the date of the day that you want.
I have a formula in a cell that is doing a vlookup to another sheet by combining the values of two cells on my spreadsheet. It's a table of names on the left and dates up top. I'm combining the name and date values into a single string value and using that as by vlookup key value, which works great. Now I need to basically do the same thing in my google script, but the date value has me at a loss. In the vlookup cell formula, the date value is the 5 digit date serial code. However when I combine the two cell values in my script, I cannot get the same 5 digit serial code out of the cell. I have tried all conversions of number, string, text, ect. What function can I use to get this 5 digit date value as a string in my script?
function serialDatevalue(){
var WB = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var NewDate = new Date();
var NewDate = WB.getRange('B1').getValue();
var JSdate = WB.getRange('B1').getValue();
Browser.msgBox(Number(NewDate));
// Some others that I have tried
// var JSdate = Date.parse(DateValue);
// var JSdate = Number(DateValue);
// var JSdate = Utilities.formatDate(DateValue, 'PST', '%');
}
for example, April 13, 2019 = 43568. I want to get this 5 digit value as a string.
I keep getting 'Sat Apr 13 2019 00:00:00 GMT-0700 (PDT)', or other longer integer values.
Please help.
From Tanaike's answer to Getting the number equalent of duration using GAS
var serialNumber = (dateObject.getTime() / 1000 / 86400) + 25569; // Reference: https://stackoverflow.com/a/6154953
The easier way to get the serialized number corresponding to a certain cell date value in Google Sheets is by using a the built-in Google Sheets function [TO_PURE_NUMBER][1]. This because Google Sheets and JavaScript, which is used by Google Apps Script, used different epoch (reference date used as 0 for the serialized numbers) and use different time units.
From https://developers.google.com/sheets/api/guides/concepts#datetime_serial_numbers
Date/Time serial numbers
Google Sheets, like most other spreadsheet
applications, treats date/time values as decimal values. This lets you
perform arithmetic on them in formulas, so you can increment days or
weeks, add or subtract two date/times, and perform other similar
operations.
Google Sheets uses a form of epoch date that is commonly used in
spreadsheets. The whole number portion of the value (left of the
decimal) counts the days since December 30th 1899. The fractional
portion (right of the decimal) counts the time as a fraction of one
day. For example, January 1st 1900 at noon would be 2.5, 2 because
it's two days after December 30th, 1899, and .5 because noon is half a
day. February 1st 1900 at 3pm would be 33.625.
Note that Google Sheets correctly treats the year 1900 as a common
year, not a leap year.
By the other hand, JavaScript use January 1, 1970 00:00 UTC as the epoch date and use milliseconds as the unit.
A word of caution: Custom code to make serialized number conversions from one to the other should consider if the spreadsheet and the Google Apps Script are using the same timezone or not.
Related
How to read value of fetched cell data as date google sheets API
Getting the number equalent of duration using GAS
I am extracting a timestamp from a cell in the format like Tue Nov 06 07:33:00 UTC 2018. Now, using vbscript code or vba code I want to subtract some minutes from the above mentioned timestamp. How can I achieve that?
split(split("Tue Nov 06 07:33:00 UTC 2018",":")(1),":")(0)
Will give you the minutes on their own. You can assign the splits to arrays, then rejoin with the correct minutes using `join
Something like so
Public Function addToTimeStamp(strTimeStamp As String, lngMinutes As Long) As String
Dim a() As String
a = Split(strTimeStamp, " ")
a(3) = DateAdd("n", lngMinutes, a(3))
addToTimeStamp = Join(a, " ")
End Function
Without going into VBA, you could separate the time stamp from the date, then work on the time stamp and adjust the date accordingly.
Assuming your dates are in the column A and that the timestamp always take the same structure, starting from row number 2
So first you create a column where there is only the time stamp, that is column B:
=MID(A2,FIND("UTC",A2)-9,8)
07:33:00
This first finds the position of "UTC" within the string then extract 8 characters starting from 9 characters to the left (accounting for the space between the time and "UTC").
Already there you can work on the minutes/hours/seconds.
Hours:
=NUMBERVALUE(LEFT(B2,2))
07
Minutes:
=NUMBERVALUE(Mid(B2,4,2))
33
Seconds:
=NUMBERVALUE(Right(B2,2))
00
You can also extract the date part of the time stamp using the same logic. Column C:
=MID(A2,FIND(B2,A2)-11,10)
Tue Nov 06
Finally you can also combine all of that into an Excel date and do your operations directly on the resulting number (This will ensure that you get a new valid date which account for incrementing/decrementing hours/days/months/years, it will also automatically account for leap years.)
Final date, including the time stamp, Column D:
=DATEVALUE(MID(A2,FIND(B2,A2)-3,2)&"-"&MID(A2,FIND(B2,A2)-7,3)&"-"&RIGHT(A2,4))+NUMBERVALUE(LEFT(B2,2))/24+NUMBERVALUE(MID(B2,4,2))/(24*60)+NUMBERVALUE(RIGHT(B2,2))/(24*60*60)
43410.3145833333
On this final number you can simply increase/decrease the number of minutes by adding it directly to it. The unit of this number is "days" so one minute is equal to 1/(24*60) and one hour is 1/24. Example of removing 33 minutes:
=D2 - 33/(24*60)
43410.2916666667
Changing the formatting to [dd/mm/yyyy hh:mm] will then result in:
06/11/2018 07:00:00
Hi I am wonder about how to set the time to live in dynamo db.
I understand that I have to create a field, could be called ttl and set the value to be deleted, but in which format innodejs do I have to save to use for the ttl field for 20 or 24 hours?
Thanks for help.
From the official DynamoDB documentation:
TTL compares the current time in epoch time format to the time stored
in the Time To Live attribute of an item. [...]
Note
The epoch time
format is the number of seconds elapsed since 12:00:00 AM January 1st,
1970 UTC.
In Javascript, you can get the number of milliseconds since the epoch by doing Date.now(). Once you have that, you can divide everything by 1000 to get the seconds (also rounding to the nearest integer value) and finally add the number of seconds in the TTL that you want.
This means that if you want to set the expiration time 24 from now, you can easily set the TTL field with the value expirationTime calculated this way:
const SECONDS_IN_AN_HOUR = 60 * 60;
const secondsSinceEpoch = Math.round(Date.now() / 1000);
const expirationTime = secondsSinceEpoch + 24 * SECONDS_IN_AN_HOUR;
I want to verify Date is valid for subscription.
Date is in UTC format.
when user creates an account i set the expiration date to be the date in 30 days.
Before each action, i want to verify the expiration date of his account.
To get the days left for user i do
let oneDay = 24*60*60*1000;
let daysLeft = (userSubscription.expired - new Date())/(oneDay))
Now i want to check that if daysLeft is 0, then do some action alerting the user.
My problem is, that is if expiration was a year ago, then days left will not be below 0 as i expected, it will be 300+.
how can i enforce it?
With this you just get the difference between those dates:
let oneDay = 24*60*60*1000;
let daysLeft = (userSubscription.expired - new Date())/(oneDay))
So the result after one year would be 365 - 30 = 335
But you need to check if userSubscription.expired is higher than new Date()
Use something from here: Compare two dates