Get total mins for today - powershell

I am looking for total mins for today,
Tried this way but not working.
$from_date = Get-Date
$Start_date = $from_date.ToShortDateString()
($from_date - $Start_date).Minute

I'd do it this way:
PS C:\> (Get-Date).TimeOfDay.TotalMinutes
651.356536988333

Don't use ToShortDateString() if you want to do further arithmetic cprocessing on the object, it'll turn it into a string.
Substract the Date property from the object and grab the TotalMinutes property value from the resulting timespan:
$from_date = Get-Date
$MinutesSinceMidnight = ($from_date - $from_date.Date).TotalMinutes
The result will be in decimal form. Use Math.Floor() if you need an integer value:
[System.Math]::Floor($MinutesSinceMidnight)

Related

Need to convert or format hhmmss to hh-mm-ss using powershell [duplicate]

I'm creating an application in PowerShell to reschedule the existing jobs in a SQL Server instance. So I have to get the active_start_time value from the sysschules table. The time value is formatted as INT HHMMSS on a 24-hour clock.
As I am using the JobSchedule class (Microsoft.SqlServer.Management.Smo.Agent.JobSchedule) in my PowerShell application, I need to convert from time value in INT to a TimeSpan value in order add to ActiveStartTimeOfDay property.
Example:
Original data: [INT] active_start_time = 10500
Expected data: [TimeSpan] ActiveStartTimeOfDay = 01h 05 min 00s
As FoxDeploy points out, treat the input number as a string!
First, you'll want to use String.PadLeft() to zero-pad the number:
$active_start_time = 10500
$start_timestamp = "$active_start_time".PadLeft(6, '0') # "010500"
Now that we have a "timestamp" of sorts, [timespan] has a ParseExact() method we can use to parse any format:
$start_timespan = [timespan]::ParseExact($start_timestamp, 'hhmmss', $null)
We can do this by taking your input int and treating it like a string. Doing that lets us call ToCharArray() which does this.
$myString = "Hi!"
$myString.ToCharArray()
H
i
!
Once it's in a char array, we can select out the positions of the characters we want by specifying its index, starting with zero, like this:
PS> $myString.ToCharArray()[0] #get's the first
H
Applying that to your scenario, we do the same to select only the numbers we want and tuck them into variables to call on later. With that, we can easily build a new [TimeSpan] object.
$inputInt = 121515
$hours= $inputInt.ToString().ToCharArray()[0..1] -join ''
$mins= $inputInt.ToString().ToCharArray()[2..3] -join ''
$secs = $inputInt.ToString().ToCharArray()[4..5] -join ''
$hours,$mins,$secs -join ":"
Output> 12:15:15
There are a lot of options to make a new [TimeSpan], we can see our choices by typing the static class name and method, and seeing what comes up.
PS> [timespan]::new
OverloadDefinitions
-------------------
timespan new(long ticks)
timespan new(int hours, int minutes, int seconds)
timespan new(int days, int hours, int minutes, int seconds)
timespan new(int days, int hours, int minutes, int seconds, int milliseconds)
That second one looks promising...
$newTimeSpan = [TimeSpan]::new($hours,$mins,$secs)
$newTimeSpan
This should get you heading in the right direction.

How to convert from a INT value HHMMSS to TimeSpan using PowerShell

I'm creating an application in PowerShell to reschedule the existing jobs in a SQL Server instance. So I have to get the active_start_time value from the sysschules table. The time value is formatted as INT HHMMSS on a 24-hour clock.
As I am using the JobSchedule class (Microsoft.SqlServer.Management.Smo.Agent.JobSchedule) in my PowerShell application, I need to convert from time value in INT to a TimeSpan value in order add to ActiveStartTimeOfDay property.
Example:
Original data: [INT] active_start_time = 10500
Expected data: [TimeSpan] ActiveStartTimeOfDay = 01h 05 min 00s
As FoxDeploy points out, treat the input number as a string!
First, you'll want to use String.PadLeft() to zero-pad the number:
$active_start_time = 10500
$start_timestamp = "$active_start_time".PadLeft(6, '0') # "010500"
Now that we have a "timestamp" of sorts, [timespan] has a ParseExact() method we can use to parse any format:
$start_timespan = [timespan]::ParseExact($start_timestamp, 'hhmmss', $null)
We can do this by taking your input int and treating it like a string. Doing that lets us call ToCharArray() which does this.
$myString = "Hi!"
$myString.ToCharArray()
H
i
!
Once it's in a char array, we can select out the positions of the characters we want by specifying its index, starting with zero, like this:
PS> $myString.ToCharArray()[0] #get's the first
H
Applying that to your scenario, we do the same to select only the numbers we want and tuck them into variables to call on later. With that, we can easily build a new [TimeSpan] object.
$inputInt = 121515
$hours= $inputInt.ToString().ToCharArray()[0..1] -join ''
$mins= $inputInt.ToString().ToCharArray()[2..3] -join ''
$secs = $inputInt.ToString().ToCharArray()[4..5] -join ''
$hours,$mins,$secs -join ":"
Output> 12:15:15
There are a lot of options to make a new [TimeSpan], we can see our choices by typing the static class name and method, and seeing what comes up.
PS> [timespan]::new
OverloadDefinitions
-------------------
timespan new(long ticks)
timespan new(int hours, int minutes, int seconds)
timespan new(int days, int hours, int minutes, int seconds)
timespan new(int days, int hours, int minutes, int seconds, int milliseconds)
That second one looks promising...
$newTimeSpan = [TimeSpan]::new($hours,$mins,$secs)
$newTimeSpan
This should get you heading in the right direction.

How to convert milliseconds to date and time in powershell?

I want convert milliseconds to date time follow the format mm/dd/yyyy in powershell, my code is below:
$data+= $dataList.Rows[$i]["ROOM_LASTVISITDATE"].ToString() + "`t"
The result of 1278504562790. So, how i can convert it to date time in powershell, please help me. Thanks
To convert a epoch/unix timestamp to a human readable date with Powershell, you can use the DateTimeOffset type.
[datetimeoffset]::FromUnixTimeMilliseconds(1278504562790).DateTime
Your code could then look like this
$lastVisited = $dataList.Rows[$i]["ROOM_LASTVISITDATE"].ToString()
$data += [datetimeoffset]::FromUnixTimeMilliseconds($lastVisited) + "`t"
Assuming the offset is the start of the UNIX epoch (01/01/1970), you could simply add the milliseconds to that offset:
$EpochStart = Get-Date 1970-01-01T00:00:00
$myDateTime = $EpochStart.AddMilliseconds(1278504562790)

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

Calculate number of days between two dates in Perl

I am using Perl to create a script that will email password expiration notifications.
I have two dates:
The date that the users password was set
The date that the users password will expire (180 days after the password was set)
use DateTime::Format::Strptime;
my $dt_pattern = DateTime::Format::Strptime->new( pattern => '%F',);
my $displayName = $entry->get_value("displayName");
my $pwdLastSet = convertWinFileTimestamp($entry->get_value("pwdLastSet"));
# Determine password expiration date
my $pwdLastSet_dt = $dt_pattern->parse_datetime($pwdLastSet);
my $pwdExpirationDate = $pwdLastSet_dt->add( days => $maxPwdAge );
# Days until password expires
# HELP!!!!!!!
sub convertWinFileTimestamp {
my $timestamp = shift;
# Strip off nanoseconds, then adjust date from AD epoch (1601) to UNIX epoch (1970)
return POSIX::strftime( "%Y-%m-%d",
localtime( ( $timestamp / 10000000 ) - 11644473600 ) );
}
I cannot figure out how to calculate the difference between the two dates!
Below is the output for each variable:
pwdLastSet: 2015-02-12
pwdExpireDate: 2015-08-11T00:00:00
Any help much appreciated...been googling like crazy but I can't figure it out...Thanks!
I tried the following lines of code:
my $pwdDaysLeft = int(($pwdExpirationDate - $pwdLastSet) / 86400);
but got the following error:
Only a DateTime::Duration or DateTime object can be subtracted from a DateTime object. at pwdreminder.pl line 65
So, we have three dates here:
The date that the password was last set. This starts off as a string in the format YYYY-MM-DD stored in $pwdLastSet, but then you parse it into a DateTime object stored in $pwdLastSet_dt.
The date that the current password expires. This is calculated by adding $maxPwdAge days to $pwdLastSet_dt, which gives a DateTime object which is then stored in $pwdExpirationDate.
The current date. Which, in your current code, you don't calculate.
What you actually want is the difference in days a between the second and third of these two dates. We can ignore the first date as is it only used to calculate the second date. I assume that you're calculating that correctly.
Hopefully, the password expiration date will always be in the future. So the calculation we want to do is:
my $diff = $pwdExpirationDate - $current_date;
As long as both of those are DateTime objects, we'll get a DateTime::Duration object back, which we can then ask for the number of days.
DateTime has a today() method that will give the current date. So our code becomes:
# Use delta_days() to get a duration object that just contains days
my $diff = $pwdExpirationDate->delta_days(DateTime->today);
print $diff->in_units('days');