I have a class of "utils" and some of the static methods. I want to call one method from the other. If I use $this it will tell me "Cannot access the non-static member 'this' in a static method or initializer of a static property." but without $this it can't find the method. I also don't want to hard code the class name - but if this is the only solution then I have to. Can you please shed some lights here? Environment: Win10/Powershell 7.1 Below please find the code
class MyDateUtils
{
Static [DateTime] ToLocalTime([String]$fromDate,[String]$fromTZ, [String]$format)
{
if($fromTZ -eq $null -or $fromTZ -eq "")
{
$fromTZ = 'Eastern Standard Time'
}
$tz = [TimeZoneInfo]::FindSystemTimeZoneById($fromTZ)
$nominalDate = FormatDate($fromDate, $format)
$utcOffset = $tz.GetUtcOffset($nominalDate)
$dto = [DateTimeOffset]::new($nominalDate.Ticks, $utcOffset)
return $dto.LocalDateTime
}
Static [DateTime] FormatDate([String]$date)
{
return FormatDate($date, $null)
}
Static [DateTime] FormatDate([String]$date,[String]$format)
{
#$dateString = $date.split(' ')[0]
if($format -ne $null -and $format -ne "")
{
return [Datetime]::ParseExact( $date, $format, $null)
}
$formatList = 'MM/dd/yyyy', 'MM/dd/yyyy HH:mm:ss', 'MM/dd/yyyy HH:mm',`
'M/d/yyyy', 'M/d/yyyy HH:mm:ss', 'M/d/yyyy HH:mm',
'MM/d/yyyy', 'MM/d/yyyy HH:mm:ss', 'MM/d/yyyy HH:mm',
'M/dd/yyyy', 'M/dd/yyyy HH:mm:ss', 'M/dd/yyyy HH:mm',
'yyyy-MM-dd', 'yyyy-MM-dd HH:mm:ss', 'yyyy-MM-dd HH:mm'
$result = $null
foreach($f in $formatList)
{
try{
$result = [Datetime]::ParseExact( $date, $f, $null)
}catch {
}
if($result -ne $null)
{
return $result
}
}
return $result
}
}
Then if I ran below from command line I got the error below:
[MyDateUtils]::ToLocalTime('2021-02-23 07:10', $null, $null)
line |
14 | $nominalDate = FormatDate($fromDate, $format)
| ~~~~~~~~~~
| The term 'FormatDate' is not recognized as a name of a cmdlet, function, script file, or executable
| program. Check the spelling of the name, or if a path was included, verify that the path is correct
| and try again.
if I added a $this prior to the FormatDate it then populated the static/this error Appreciate for your help