I have the following
foreach($res in $result1)
{
$ed = $res.EVENT_DATE
}
$ed is
29 September 2015 00:00:00
(It comes out of a MySQL Database as '2015-09-29' - but I'm assuming powershell is being 'clever' and converting it).
However, I need it to display as '
2015-09-27
I tried:
$ed = $res.EVENT_DATE
$ed = get-date -date $ed
With the intention of then formatting it accordingly, But this gives me
Get-Date : Cannot bind parameter 'Date' to the target.
Exception setting "Date": "Object reference not set to an instance of an object."
What is the correct way of formatting this to display as required?
How Powershell displays it depends on your locale info.
For example:
D:\> get-date "29 September 2015 00:00:00"
Tuesday, September 29, 2015 12:00:00 AM
D:\> get-date "29 September 2015 00:00:00" -Format yyyy-MM-dd
2015-09-29
so you might try this:
foreach($res in $result1)
{
$ed = get-date $res.EVENT_DATE -format yyyy-MM-dd
}
Related
I have just started to learn Powershell, and there is one thing I just can't wrap my head around. See below:
> Write-output $(Get-Date -DisplayHint Date)
//Expect: Tuesday, November 3, 2020
//Got: Tuesday, November 3, 2020
> Write-output "$(Get-Date -DisplayHint Date)"
//Expect: Tuesday, November 3, 2020
//Got: 11/03/2020 20:42:27
For the second line with quotation interpolation, can someone explain why it is showing a different format?
Thank you,
That's the default format for the ToString() method in the current culture. This output is the result of "turning it into a string". The following examples all result in similar output as they are converting to string.
Write-Host (converts the output to a string)
Write-Host (Get-Date -DisplayHint Date)
11/3/2020 11:46:00 PM
ToString()
(Get-Date -DisplayHint Date).ToString()
11/3/2020 11:48:55 PM
-as operator
(Get-Date -DisplayHint Date) -as [string]
11/03/2020 23:49:37
String interpolation
"{0}" -f (Get-Date -DisplayHint Date)
11/3/2020 11:51:27 PM
And of course you already discovered converting to string by enclosing in quotes.
If you want to control how it's formatted, here are a few ways.
(Get-Date).ToLongDateString()
Tuesday, November 3, 2020
(Get-Date).ToString("dddd, MMMM d, yyyy")
Tuesday, November 3, 2020
Get-Date -f "dddd, MMMM d, yyyy"
Tuesday, November 3, 2020
Date can be showed in a customised way when it is converted into string.
In the above code you have enclosed in double quotes, which powershell treats it as a string.
(Get-Date -DisplayHint Date).toString() may also give you same result.
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
I have a date I am reading from somewhere so I am retrieving as a string value. My Culture is de-DE but need the time to have the AM/PM for when the script runs in en-US:
$date = 10.04.2018 14:40:20
$NewDate = Get-Date -Date $date -Format "dd MMM yyyy h:mm:ss tt"
What I want is $NewDate to be 10 Apr 2018 2:40:20 PM but am only able to get 10 Apr 2018 2:40:20. In english the tt translates to an AM/PM just fine, but how do I get it here?
If you want to rely on a certain date string, no matter where and with what culture information your script is run, you have to define a fixed culture info for your output:
$date = '10.04.2018 14:40:20'
$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture('en-US')
(Get-Date $date).ToString('dd MMM yyyy h:mm:ss tt', $culture)
Output:
10 Apr 2018 2:40:20 PM
The output will always be the same, even on your 'de-DE' machine. You can read more about date formatting in my answer here.
Look at this article, and adapt this code to achieve what you want.
$cultures = "en-US","en-GB","fr-CA","fr-FR","ms-MY","zh-HK", "de-DE"
foreach ($c in $cultures)
{
$culture = New-Object system.globalization.cultureinfo($c)
$date = get-date -format ($culture.DateTimeFormat.LongTimePattern)
New-Object psobject -Property #{"name"=$culture.displayname; "date"=$date}
}
Also be sure to look at the various properties of $culture.DateTimeFormat.
The $date variable is not a datetime type. Actually, this assignment will not run. I assume you meant to make it a string. Use ParseExact() to convert it to a date.
$date = [datetime]::ParseExact('10.04.2018 14:40:20','M.d.yyyy H:m:s', $null)
$NewDate = Get-Date -Date $date -Format "dd MMM yyyy h:mm:ss tt"
I have some code that checks for a valid date, simple example:
[datetime]::ParseExact(
'201809222130',
'yyyyMMddHHmm',
[System.Globalization.CultureInfo]::InvariantCulture
)
This outputs:
Saturday, September 22, 2018, 9:30:00 PM
I'm trying to display the hour in 24h format, desired output:
Saturday, September 22, 2018, 21:30:00 PM
It is possible to display 24h format using the Get-Date Cmdlet, e.g.: Get-Date -UFormat %R, but I can't use this when creating a [datetime] object.
How can I display 24h format?
There isn't any reason you can't use Get-Date with the [datetime] object your code creates. For example:
$d = [datetime]::ParseExact(
'201809222130',
'yyyyMMddHHmm',
[System.Globalization.CultureInfo]::InvariantCulture
)
Get-Date $d -UFormat %R
You could also use the .ToShortTimeString() method:
$d.ToShortTimeString()
Or .ToString and specify the tokens:
$d.ToString('HH:mm')
The PowerShell answer
Using get-date -format
HH is 24 hour
hh is 12 hour
get-date -format "yyyy-MM-dd HHmmss"
2021-04-12 183340
get-date -format "yyyy-MM-dd hhmmss"
2021-04-12 063340
Mark Wragg beat me to it!
To add to his answer, you are getting this output because of your region settings. On my machine, the same code returns:
22 September 2018 21:30:00
The reason for this is because my region settings look like this:
You could change your Global Region settings, but it's better to get it done with code.
I have a variable, $date, containing 24 June 2012 00:00:00.
How do I convert this to 24/06/2012?
Use the Get-Date cmdlet together with the Format parameter:
PS> $date = '24 June 2012 00:00:00'
PS> Get-Date $date -Format 'dd/MM/yyyy'
24/06/2012
I tried reading a file with dates formatted day-month-year
The answer above did not work for me, I found a different solution on how to parse my dates and check which one is newer than the current date. This is my adapted code.
$currdateobj = Get-Date
$STARTDATE = "12-05-2017" // specific non-default date format
[DateTime]$startdateobj = [DateTime]::ParseExact($STARTDATE,"dd-MM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture)
if ($startdateobj -lt $currdateobj)
{
// ....
}