Increase number each day - powershell

I need to create a variable in PowerShell that increases with one each day. I'm going to use this variable in an email subject to define the Day Number as part of a test schedule. e.g. "Test - Day 38", when the script runs the next day it must ready "Test - Day 39".
I obviously can't use the date and AddDays, because the count is not limited to the number of days in the month.

Here is the code, $days is the result
# when counting starts, the first day
$startDate = [datetime]'2014-01-12'
# elapsed days (+ 1 in order to start with "day 1")
$days = [int]((Get-Date) - $startDate).TotalDays + 1
# result string
"Test - Day $days"
This code outputs (today)
Test - Day 38

Here's what I propose (it does involve using the date cmdlets):
When the test first runs, store the runtime in a file.
For example:
if (!(Test-Path startTime.txt)) {
get-date | out-file startTime.txt
}
Each time the test runs subsequently, read in the first_runtime from the file.
Subtract the current date (using get-date) from first_runtime.
This will have a .Days member you can extract to retrieve the number of Days elapsed.
Days : 2
Hours : 0
...

Related

GSheets - Time between date and now()

Trying different things and combos, but can't get it right. Times and dates always get me.
I'm simply trying to compare now() and a date/time and show "in 2 days 6 hrs 30 mins" or "3 days 1 hr 20 mins ago" and I'm guessing someone has done this already?
So, let's say the date in column A is 2023-01-24 10:00 and now it is 2023-01-25 11:05, then Col B should say "1 day 1 hr 5 mins ago"
I've tried duration(), date/time formatting the cell, days(..), but I can't find something that works reliably.
Another thing you could try:
=INT(NOW()-A1)&" d "&TEXT(NOW()-A1,"h \hr m \min a\go")
=NOW()-A1 will actually calculate the difference between Now and that time, BUT consider that the time is updated only when you make a change, it's not a countdown second by second. You can add an updater per minute but not more than that. Go to File - Settings and set On change and every minute:
If you need a specific format like that you mentioned you should then do calculations to add them. If you only need days, hours, minutes and seconds, you can do the next checkings and concatenations:
=LAMBDA(dif,
IF(INT(dif),INT(dif)&" days ","")
&IF(HOUR(dif),HOUR(dif)&" hours ")
&IF(MINUTE(dif),MINUTE(dif)&" minutes ")
&IF(SECOND(dif),SECOND(dif)&" seconds")&" ago")
(Now()-A1)
please try:
=TRIM(LAMBDA(y,IF(NOW()-A1<1,"0 days",IF(y=1,y&" "&"day",y&" "&"days")))(DATEDIF(A1,NOW(),"D"))&" "&
LAMBDA(y,IF(y=1,y&" "&"hr",y&" "&"hrs"))(HOUR(NOW()-A1))&" "&
LAMBDA(y,IF(y=1,y&" "&"min",y&" "&"mins"))(MINUTE(NOW()-A1))&" ago")
try:
=INDEX(IF(ISDATE_STRICT(A2:A), TRIM(FLATTEN(QUERY(TRANSPOSE(
IFERROR(LAMBDA(a, LAMBDA(x, IF(x=0,,IF(x>1, x&a&"s", x&a)))
(DATEDIF(A2:A, NOW(), {"Y", "YM", "MD"})))({" year", " month", " day"}))),,9^9))), ))

Extract time from date time and find difference between 2 times

I am trying to convert EPOC time to date time and need to extract the time only from that
I am doing below
$min = $Time_Start | measure -Minimum
$max = $Time_End | measure -Maximum
[datetime]$oUNIXDatemin=(Get-Date 01.01.1970)+([System.TimeSpan]::fromseconds($min.Minimum))
$oUNIXDatemin_1 = $oUNIXDatemin.ToString("HH:mm:ss")
[datetime]$oUNIXDatemax=(Get-Date 01.01.1970)+([System.TimeSpan]::fromseconds($max.Maximum))
$oUNIXDatemax_1 = $oUNIXDatemax.ToString("HH:mm:ss")
Problem is while converting I am getting $oUNIXDatemin_1 and $oUNIXDatemax_1 value like
$oUNIXDatemin_1
12 October 2021 07:46:46
$oUNIXDatemax_1
12 October 2021 21:16:04
My EPOC values are
$min.Minimum
1634024806
$max.Maximum
1634073364
Please let me know what is wrong here. Need to find the difference in HH:mm:ss format.
In PowerShell, you'd usually use a format string. Subtracting two PowerShell datetimes returns a value of type Timespan, which is well-behaved over a span of more than 24 hours.
([datetime]"12 October 2021 21:16:04" - [datetime]"12 October 2021 07:46:46") -f "HH:mm:ss"
13:29:18
Be careful here. Both intervals (durations) and time (of day) have the same format, but different meanings. For example, it makes sense to multiply the interval "01:00:00" (1 hour) by 3 to get three hours; it doesn't make sense to multiply the time "01:00:00" (1 o'clock AM) by 3.
I'm sure the overall calculation can be simplified, but it's too early for me.

How to get last Sunday's date?

I need to show last Sunday's date in a cell for a weekly report that I'm creating on google sheets. I've been googling to find a solution and the closest I found is this:
=TODAY()+(7-WEEKDAY(TODAY(),3))
But this gives next Monday's date. Any idea how to modify this to show last Sunday's date? Alternately, do you have another way to solve this problem?
The formula you're looking for would be:
=DATE(YY, MM, DD) - (WEEKDAY(DATE(YY, MM, DD)) - 1) - 7
// OR
=TODAY() - (WEEKDAY(TODAY()) - 1) - 7
Depending on what you take to be "last Sunday," you can simplify/factor this:
If you take "last Sunday" to mean, "the Sunday which has most recently happened:"
=DATE(A2,B2,C2) - WEEKDAY(DATE(A2,B2,C2)) + 1
If you take "last Sunday" to mean, "the Sunday which took place during the previous week:"
=DATE(A4,B4,C4) - WEEKDAY(DATE(A4,B4,C4)) - 6
Working through it:
=TODAY() - (WEEKDAY(TODAY()) - 1) - 7
TODAY()
// get today's date, ie. 22/11/2019
WEEKDAY(TODAY())
// get the current day of the week, ie. 6 (friday)
-
// take the first date and subtract that to rewind through the week,
// ie. 16/11/2019 (last saturday, since saturday is 0)
- 1
// rewind back one less than the entire week
// ie. 17/11/2019 (this sunday)
- 7
// rewind back to the sunday before this
// sunday, ie. 10/11/2019
Hopefully this explanation explains what the numbers at the end are doing. + 1 takes you from the Saturday of last week to the Sunday of the current week (what I would call "this Sunday"), and - 6 takes you back through last week to what I would call "last Sunday."
See here:
try:
=ARRAYFORMULA(TO_DATE(FILTER(ROW(INDIRECT(VALUE(TODAY()-6)&":"&VALUE(TODAY()))),
TEXT(ROW(INDIRECT(VALUE(TODAY()-6)&":"&VALUE(TODAY()))), "ddd")="Sun")))
if today is Sunday and you want still the last Sunday then:
=ARRAYFORMULA(IF(TEXT(TODAY(), "ddd")="Sun", TODAY()-6,
TO_DATE(FILTER(ROW(INDIRECT(VALUE(TODAY()-6)&":"&VALUE(TODAY()))),
TEXT(ROW(INDIRECT(VALUE(TODAY()-6)&":"&VALUE(TODAY()))), "ddd")="Sun"))))
Using monday as 1 index, this will return the previous sunday or today if it is sunday
=if((7-WEEKDAY(today(),2))>0,today()-(7-(7-WEEKDAY(today(),2))),today()+(7-WEEKDAY(today(),2)))
One can select for other days of the week by changing the number "7" directly before "-WEEKDAY(today(),2)" in the three places that pattern exists.

Retrieve datetime object in Powershell without the time portion

Is it possible to retrieve only the date portion of a datetime object in PowerShell? Reason being I need to compare the LastWriteTime property of files with today's date to determine whether to backup a file or not. As-is a datetime object includes the time as well which will always evaluate to false when I do something like:
if ($fileDate -eq $currentDate) {
# Do backup
}
I haven't found anyway to do this. If we use the format operator or a method, it converts the object to a string object. If you try to convert that back to a datetime object, it appends the time back onto the object. Probably something simple, but I've been looking at this script for a while and that's the last part that's breaking.
EDIT: As #jessehouwing points out in the comments below, my answers are unnecessarily complicated. Just use $datetime.Date.
A couple of ways to get a DateTime without any time component (ie set to midnight at the start of the date in question, 00:00:00):
$dateTime = <some DateTime>
$dateWithoutTime = $dateTime.AddSeconds(-$dateTime.Second).AddMinutes(-$dateTime.Minute).AddHours(-$dateTime.Hour)
or
$dateTime = <some DateTime>
$dateWithoutTime = Get-Date -Date ($dateTime.ToString("yyyy-MM-dd"))
I ran each version in a loop, iterating 100,000 times. The first version took 16.4 seconds, the second version took 26.5 seconds. So I would go with the first version, although it looks a little more complicated.
Based on answers found here: https://techibee.com/powershell/powershell-how-to-query-date-time-without-seconds/2737 (that article is about stripping just the seconds from a DateTime. But it can be extended to stripping hours, minutes and seconds).
Assuming $fileDate is not a dateTime object, then you can just convert both to strings and format them.
if ($fileDate.ToString() -eq $currentDate.ToString("dd/MM/yyyy")) {
# Do backup
}
This will not answer how to remove time on datetime, but to do your validation purpose of identifying when to backup.
I do suggest to subtract your two given date values and compare the result if total hours are already met to do your backup.
if (( $currentDate - $fileDate ).TotalDays > 7) {
# Do Backup
}
you can also validate for the following
Days :
Hours :
Minutes :
Seconds :
Milliseconds :
Ticks :
TotalDays :
TotalHours :
TotalMinutes :
TotalSeconds :
TotalMilliseconds :
Assuming $currentTime contains a DateTime object, you can retrieve a new DateTime object with the same date but with the time portion zeroed like this:
$midnight = Get-Date $currentTime -Hour 0 -Minute 0 -Second 0 -Millisecond 0

Convert unix time to month number?

Using os.time how can I get how many months have passed since the unix epoch (Unix Timestamp)
I just need it for a month ID, so any kind of number would be fine, as long as it changes every month, and it can be reversed to get the actual month.
local function GetMonth(seconds)
local dayduration,year = 3600*24
local days={31,0,31,30,31,30,31,31,30,31,30,31}
for i=1970,10000 do -- For some reason too lazy to use while
local yeardays = i%4 == 0 and i%100 ~= 0 and 366 or 365
local yearduration = dayduration * yeardays
if yearduration < seconds then
seconds = seconds - yearduration
else
year = i break
end
end
days[2]=(year%4==0) and 29 or 28
seconds = seconds%(365*24*3600)
for i=1,12 do
if seconds>days[i]*dayduration then
seconds=seconds-days[i]*dayduration
else
return --i + year*12 <-- If you want a unique ID
end
end
end
Currently, it'll give the number 2, since it's February. If you uncomment the code at the end for the unique ID, you'll get 554 instead, meaning we're currently at the 554th month since the epoch.
As Jean-Baptiste Yunès said in his answer's comments, I'm not sure if your sentence:
NOTE: This is for Lua, but I'm unable to use os.date
meant you have no os.date, or that you don't know how to use it. You have an answer for both cases, you can use the one you need.
This may do the trick:
print (os.date("*t",os.time())["month"])
os.time() gives you the current date as a number. os.date("*t",...) converts it into a table in which the month equals to the number of the month corresponding to the date.