Convert date and time string into datetime - powershell

I've got a variable of type string which looks something like this
$string = "07/07/2019 18:00". I want to convert this variable into an variable of type datetime. The format should be MM/DD/YYYY HH:MM
$date = '07/07/2019'
$time = '18:00'
$datetime = $date + ' ' + $time
$datetime = [datetime]::ParseExact('$datetime', 'MM/DD/YYYY_HH:MM', $null)
Using the code above, I get an error message telling me:
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
Is there another way to go?

Your format string used wrong specifiers, namely DD and YYYY; see custom date and time formats.
Change your code to
$date = '07/07/2019'
$time = '18:00'
$datetime = $date + ' ' + $time
$datetime = [datetime]::ParseExact($datetime, 'MM/dd/yyyy HH:mm', $null)
$datetime
Also be aware to pass $datetime as reference and not as single quoted string.
You find above code under this link.

[datetime]'07/07/2019 18:00'
Sunday, July 7, 2019 6:00:00 PM
Or
[datetime]'7/7'
[datetime]'18:00'
[datetime]'6pm'
Then you can add or subtract them, but then the answer is a [timespan].

Related

Powershell - Find the latest Friday

How can the following code be modified to identify the latest Friday within the past week (instead of the next one), but with formatting?
$Date = #(#(0..7) | % {$(Get-Date).AddDays($_)} | ? {$_.DayOfWeek -ieq "Friday"})[0]
Source: https://stackoverflow.com/a/23939203/5651418
The post you linked to offers a more elegant solution, which you can adapt as follows:
# Get the most recent Friday relative to the given date,
# which may be that date itself.
$mostRecentFriday =
($date = Get-Date).AddDays((-7 - $date.DayOfWeek + [DayOfWeek]::Friday) % 7)
If you want to create a formatted string representation of the resulting [datetime] instance (all examples below yield something like '07 01 2022':
To use Unix-style format specifiers, use Get-Date's -UFormat parameter:
Get-Date $mostRecentFriday -UFormat '%d %m %Y'
To use .NET's format specifiers, use Get-Data's -Format parameter:
Get-Date $mostRecentFriday -Format 'dd MM yyyy'
Alternatively, pass the format string to the [datetime]
instance's .ToString() method:
$mostRecentFriday.ToString('dd MM yyyy')
If I understood correctly, your expected output would be 1 7 2022, I would personally use a do loop that stops as soon as the DayOfWeek Property of the DateTime instance is Friday:
$date = [datetime]::Now
do {
$date = $date.AddDays(-1)
} until($date.DayOfWeek -eq [DayOfWeek]::Friday)
$date.ToString("d M yyyy")
I noticed that some Get-Date -UFormat specifiers didn't seem to work when attempting to incorporate them into an output string.
Should anyone need to incorporate some rarely needed ones (like 'Week of Year' (%G), 'Day of Year (%j), etc) you could preset needed variables and add them to the output string:
$DayOfYear = (Get-Date -UFormat %j)
$WeekOfYear = (Get-Date -UFormat %V)
$Date = #(#(0..7) | % {$(Get-Date).AddDays(-$_)} | ? {$_.DayOfWeek -ieq "Wednesday"})[0].ToString("MM-dd-yyyy|Week $WeekOfYear|'Day' $DayOfYear")
I imagine someone could incorporate all the code into one Powershell command.
Additional Get-Date -UFormat specifiers: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.2#notes

Subtracting time in powershell

I use the following time code:
$time = [DateTime]::UtcNow | get-date -Format "yyyyMMddHH"
$m2=$time-02 # trying to subtract 2 hours
However, for times like 2021021701, subtracting 2 gives me 2021021699. How can I have the time display in the correctly?
Another way. The 2nd arg can be a datetime or a timespan. $time is a datetime.
$time = get-date
$m2 = $time - [timespan]'2:0'
$m2
Wednesday, February 17, 2021 7:31:59 PM
To perform date calculations, operate on [datetime] (System.DateTime) instances and use that type's methods, such as .AddHours(); only after that should you create the desired string representation:
# Get the current UTC time as a [datetime] instance.
$time = [DateTime]::UtcNow
# Subtract 2 hours.
$m2Time = $time.AddHours(-2)
# Create the desired string representation.
$m2 = Get-Date $m2Time -Format 'yyyyMMddHH'

Date time format in PowerShell returning incorrect date in powershell

I want to change text 11.30 to time format 11:30 using [datetime] in powershell
$Stime = "11.30"
$time = "{00:hh:mm}" -f [datetime]$Stime
Write-Host $time
This code returns value 12:00
I tried this too -
$fromtime = "11.30"
[datetime]$fromtime12hrFormat = ([datetime]$fromtime)
$fromtime12hrFormat.ToString("hh:mm:ss")
This code returns value 12:00
"11.30" cast to [datetime] with en-US locale will be interpreted as "November 30" at midnight.
Use DateTime.ParseExact() instead:
'{0:HH:mm}' -f [datetime]::ParseExact($Stime, 'HH.mm', $null)

Powershell get date from log file

I would like to get date from the log file text.
Text in log file.
Error code. 200105. Simple text and so on -------------> it should get date as 2020 Jan 05
Error code. 2000207. Simple text and so on -------------> it should get date as 2020 Feb 07
I try this but it doesnt work.
Get-Date "200105" -format "y-m-d" but it doesnt work.
I also try "200105" | Date but still same issue
This does work [datetime]::ParseExact("120105", "y.m.d", $null) but how do I get just the date but ignore all of the other text
If you want a shorter version you can do that by piping the output as follows
$date = [datetime]::ParseExact($text2, "y.M.d", $null)
$date | Get-Date -Format dd-MMMM-yyyy
Or
$date.ToString("yyyy MMMM dd")
Your second example 2000207 is invalid because of the extra 0 in there.
I would use the TryParseExact method here to see if what you have got is actually a parsable datetime string.
$logLine = 'Error code. 200105. Simple text and so on'
if ($logLine -match '^Error code\s*\.?\s*(\d{6})') {
$date = Get-Date # any valid DateTime object will do
if ([datetime]::TryParseExact($Matches[1], 'yyMMdd', [cultureinfo]::InvariantCulture, 0, [ref]$date)) {
# do something with the date found. For demo, just output in the console
"Found a date: $date"
}
}
You are probably reading the log file line-by-line, something like:
Get-Content -Path 'TheLogFile' | ForEach-Object {
if ($_ -match '^Error code\s*\.?\s*(\d{6})') {
$date = Get-Date # any valid DateTime object will do
if ([datetime]::TryParseExact($Matches[1], 'yyMMdd', [cultureinfo]::InvariantCulture, 0, [ref]$date)) {
# do something with the date found. For demo, just output in the console
"Found a date: $date"
}
}
}
According to the documentation, Get-Date converts a string to a date if it recognises the date format from the locale settings.
For instance, in UK it recognises Get-Date "2020/03/21" but not Get-Date "20200321"
The format string is only used for formatting the current date.
This works: the number of characters in the format string represents the size of the input (it matches the number of digits in the day and year - it is more complicated for months) and M represents months (m represents minutes).
PS /home/alistair> [datetime]::ParseExact("200321","yyMMdd",$null)
Saturday, 21 March 2020 00:00:00

PowerShell - formatting date to yyMMdd format

I run a PowerShell script that passes a parameter, such as "20160428".
I need to format this into yyMMdd (i.e., getting "160428" as the result). I could just strip out the "20", but I would like to get this right. For such I did so many attempts, such as:
#$COBDATE= '{0:yyMMdd}' -f $COBDATE
#$COBDATE = ([datetime]::ParseExact($COBDATE, "yyMMdd", [System.Globalization.CultureInfo]::InvariantCulture )).DayOfWeek
And the last one:
$COBDATE = ("{0:yyMMdd}" -f [datetime]::parse($COBDATE))
The below works, but once I replace "Get-Date" by my date "20160428" it just prints out the yyMMdd string.
$b = (Get-Date).AddDays(-1).ToString("yyMMdd")
So if I try this:
$input = "20160428"
$format = "yyMMdd"
$input_toDate_up = [DateTime]::ParseExact($input, $format, $null).ToString($format)
$input_toDate_up
It just says that the string is not a valid Date Time, which seems to be the root cause.
How can I fix this?
$Input = "20160428"
Get-Date -Year $Input.Substring(0,4) -Month $Input.Substring(4,2) -Day $Input.Substring(6,2) -Format "yyMMdd"
I think for one $input is a reserved variable so you shouldn't use it as nothing will really work in there as you expect. See here about_Automatic_Variables
I have used this drawn out substring process before with varied abstract date formats.
$dateinput = "20160428"
$dateformat = "yyMMdd"
Get-Date($dateinput.Substring(4,2) + "/" + $dateinput.Substring(2,2) + "/" + $dateinput.substring(0,4)) -Format $dateformat
I'm sure there is a shorter regex method, but that is not under my hat yet.