Powershell what is the time format - powershell

2017-05-05 12:03:02 -0400 (Fri, 05 May 2017)
what time format is the above in powershell??
i need the same format to compare with today time in powershell.
Get-Date -format

Since this is a follow-up question, you should mention this.
To convert a string containing a datetime based on UTC with a timezone offset,
use [datetime]::ParseExact(). You should change the RegEx from previous Q&A to only contain the datetime without the redundant information in parentheses.
[datetime]::ParseExact("2017-05-05 12:03:02 -0400","yyyy-MM-dd HH:mm:ss zzzzz",$Null)
This will convert to local time (and correctly include the DST aka daylight saving time at that date)
Sample output here with timezone +1 and DST active to:
2017-05-05 18:03:02 +02:00
Or more universal with .ToString('U') and my German locale settings to:
Freitag, 5. Mai 2017 16:03:02
To get the difference to [datetime]::Now simply subtract and choose a property from
> [datetime]::Now - [datetime]::ParseExact("2017-05-05 12:03:02 -0400","yyyy-MM-dd HHH:mm:ss zzzzz",$Null)
Days : 593
Hours : 20
Minutes : 15
Seconds : 35
Milliseconds : 615
Ticks : 513081356156056
TotalDays : 593,844162217657
TotalHours : 14252,2598932238
TotalMinutes : 855135,593593427
TotalSeconds : 51308135,6156056
TotalMilliseconds : 51308135615,6056

You can build more or less any format you like using the DateTime Format Strings and either the format operator (-f) or the ToString() method. For example:
(Get-Date).ToString("yyyy-MM-dd hh:mm:ss")
Which gives something like this:
2018-12-20 12:50:53
If you want to go the other way, you can do it like this:
Get-Date "2017-05-05 12:03:02 -0400"
This converts your string to an actual DateTime object, which can be directly compared to any other DateTime. So, to check if your target date is before now, for example, do something like this:
(Get-Date "2017-05-05 12:03:02 -0400") -lt (Get-Date)

Related

Setting timezone = "Asia/Kolkata" in #jsonformat and storing it in java.sql.timestamp converts 12 pm to 1 pm timesatmp to 00 am in spring hibernate

I am using
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss", timezone = "Asia/Kolkata")
private Timestamp startDateTime;
to store timestamp comes in json as a string.
But the problem is it converts time between 12 pm to 1 pm into 00 am.
E.g. 2021-10-25 12:30:00 gets converted to 2021-10-25 00:30:00.
Any help will be appreciated.
Thank you.
The root cause of the problem is that you have used h instead of H. Note that h is used for 12-hour time format (i.e. time with AM/PM marker) while H is used for 24-hour time format. So, the solution to your problem is to change the format to dd-MM-yyyy HH:mm:ss.
In case, you want the AM/PM marker in the time, change the format to dd-MM-yyyy hh:mm:ss a.

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.

Odd Date/Time format

I have a single program in the Uninstalls registry key with an odd date/time. The value reported is '1533407816', but the actual date is most likely '20180804', which is what all the other Autodesk products installed that day report as.
I am using [datetime]::ParseExact($program.GetValue('InstallDate'),'yyyyMMdd',$null) to convert those dates to a proper DateTime, but not sure what mechanism I need for the odd one. Or if it's even meaningful data.
The value is likely a Unix time stamp, which is the number of seconds that have elapsed since midnight (UTC) of 1 Jan 1970.
You can convert this value to a [datetime] instance in local time as follows:
[DateTimeOffset]::FromUnixTimeSeconds(1533407816).LocalDateTime
To get a UTC [datetime] instance instead, use .UtcDateTime.
Alternatively, work directly with the [System.DateTimeOffset] instance returned by [DateTimeOffset]::FromUnixTimeSeconds().
Note:
Unix time stamps are signed 32-bit integers ([int]) in seconds.
As an aside, this means that the latest date that they can represent is in the year 2038, a limitation known as the Year 2038 problem.
By contrast, [datetime] instances have a resolution of 100 nanoseconds, called ticks, stored in the .Ticks property, whose type is [long] ([System.Int64] a signed 64-bit integer). To manually convert seconds to ticks, multiply them with 10000000L (1e7L).
Simple helper function:
function convertFrom-UnixTime {
param([int] $Value)
[DateTimeOffset]::FromUnixTimeSeconds($Value).LocalDateTime
}
In action, in the Eastern Time Zone, using the en-US culture:
PS> convertFrom-UnixTime 1533407816
Saturday, August 4, 2018 2:36:56 PM
Expressed in Coordinated Universal Time (UTC) (en-US culture):
PS> (convertFrom-UnixTime 1533407816).ToUniversalTime()
Saturday, August 4, 2018 6:36:56 PM
That odd value to me looks like a Unix Timestamp.
Here's a function that will convert it to a normal date
function ConvertFrom-UnixTimeStamp([Int64]$unixTimeStamp, [switch]$asUtc) {
if ($unixTimeStamp -gt 253402430399) {
Write-Error "Cannot convert $unixTimeStamp to DateTime. Only integer values up to 253402430399 are valid."
}
elseif ($unixTimeStamp -gt [Int32]::MaxValue) {
Write-Warning "The given value exceeds the [Int32]::MaxValue and therefore enters the Year2038 Unix bug.."
}
[DateTime]$origin = New-Object System.DateTime 1970, 1, 1, 0, 0, 0, 0, Utc
if ($asUtc) { return $origin.AddSeconds($unixTimeStamp) }
return ($origin.AddSeconds($unixTimeStamp)).ToLocalTime()
}
ConvertFrom-UnixTimeStamp 1533407816 -asUtc will yield a DateTime object:
Saturday, August 4, 2018 18:36:56

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

How to get last day of specified month in powershell

I need to get the last day of a month previous from specified.
I have a string (file name), which contains a date in its end. I need to capture the date (already done) and get the last date of the preceding month. For example the string is "proemail vytvoreni_9.2017 2017-10-16", so I need to get 30th September 2017. This is what I have now:
$Report = Read-Host "File name"
$Date = [datetime]$Report.Substring($Report.get_Length()-10)
$Last_month = $Date.AddMonths(-1)
$Date_text = $Last_month.ToString().Substring(3,7)
$month_year = ($Date_text.Split("."))
$days_count = [datetime]::DaysInMonth($month_year[1],$month_year[0])
$days_count = $days_count.ToString()
$month = $month_year[0]
$year = $month_year[1]
$Date_limit = [DateTime]($month,$days_count,$year)
All works well, except for the last row, that returns this error: Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.DateTime". I tried to convert $month and $year to string by .ToString() method, but it didn't help
(Get-Date).AddDays(-$(Get-Date).Day)
Saturday, September 30, 2017 2:36:19 PM
((Get-Date).AddDays(-$(Get-Date).Day)).Day
30
$filename = "proemail vytvoreni_9.2017 2017-10-16"
# Take the date from the filename
$sub = $filename.Substring($filename.Length-10)
# make it into a date format
$filedate = Get-Date -Date $sub
# take that date 2017-10-16 and substracts its own days so in this case substract 16 days, then show me the date
(($filedate).AddDays(-$filedate.Day)).Date
Output:
Saturday 30 september 2017 0:00:00
I've looked at this problem and different solution for this for awhile and here is my answer.
Create any date you want. Here is an easy way to get the month you want.
$date = [datetime]::Parse("11/2019")
Then simply add the next month and remove one day. p
$date.AddMonths(1).AddDays(-1)
Hope this helps somebody else.