Tinus EngOps Wiki

Logo

OpsaC - Operating as PowerShell code

Links

Home

PowerShell Blog

PowerShell Index

PowerShell Search

Additional Websites

View my GitHub Profile

View my GitHub Gists

View Tinus IT Wiki

View my Photo Website

DateTime

tags: PowerShell categories: PowerShell-Basic

Table of Contents

DateTime Object

Get-Date

Donnerstag, 7. Februar 2019 19:36:43

DisplayHint

Get-Date -DisplayHint Date

Donnerstag, 7. Februar 2019

Time in 12-hour format

Get-Date -f 'yyyy-MM-dd hh:mm:ss'

2019-02-07 07:37:29

Time in 24-hour format

Get-Date -f 'yyyy-MM-dd HH:mm:ss'

2019-02-07 19:37:10

Time with millisecond

Get-Date -f 'yyyy-MM-dd HH:mm:ss.fff'

2019-05-23 19:54:02.050

Time Difference between Dates

$StartDate = Get-Date('06.10.2018 21:00')
$EndDate   = Get-Date('08.10.2018 12:00')
New-TimeSpan -Start $StartDate -End $EndDate | Select Days, Hours, Minutes, Seconds

Days Hours Minutes Seconds
---- ----- ------- -------
   1    15       0       0

Convert from decimal hours

function Convert-DecimalToTime {
    Param(
        [float]$decimalHour
    )

    $hours = [math]::Floor($decimalHour)

    $minutesDecimal = $decimalHour - $hours
    $minutes = ($minutesDecimal * 60)
    $minutesInt = [int]$minutes
    $formattedMinutes = "{0:00}" -f $minutesInt

    return "$($hours):$($formattedMinutes)"
}

Convert-DecimalToTime -decimalHour 6.72

Convert to decimal hours

function Convert-TimeToDecimal {
    Param(
        [string]$timeString
    )

    $null = $timeString -match '^\d{1,2}'
    $hours = $Matches[0]
    
    $null = $timeString -match '\d{1,2}$'
    $minutesDecimal = [math]::Round([int]$Matches[0] * 100 / 60)

    return "$($hours).$($minutesDecimal)"
}

Convert-TimeToDecimal -timeString '6:43'

The magic of computers culture

Get the current Culture

$CurrentCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture; $CurrentCulture

[System.Threading.Thread]::CurrentThread.CurrentCulture.DateTimeFormat

Output:

LCID             Name             DisplayName
----             ----             -----------
1033             en-US            English (United States)
AMDesignator                     : AM
Calendar                         : System.Globalization.GregorianCalendar
DateSeparator                    : /
FirstDayOfWeek                   : Sunday
CalendarWeekRule                 : FirstDay
FullDateTimePattern              : dddd, MMMM d, yyyy h:mm:ss tt
LongDatePattern                  : dddd, MMMM d, yyyy
LongTimePattern                  : h:mm:ss tt
MonthDayPattern                  : MMMM d
PMDesignator                     : PM
RFC1123Pattern                   : ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern                 : M/d/yyyy
ShortTimePattern                 : h:mm tt
SortableDateTimePattern          : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator                    : :
UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern                 : MMMM yyyy
AbbreviatedDayNames              : {Sun, Mon, Tue, Wed…}
ShortestDayNames                 : {Su, Mo, Tu, We…}
DayNames                         : {Sunday, Monday, Tuesday, Wednesday…}
AbbreviatedMonthNames            : {Jan, Feb, Mar, Apr…}
MonthNames                       : {January, February, March, April…}
IsReadOnly                       : True
NativeCalendarName               : Gregorian Calendar
AbbreviatedMonthGenitiveNames    : {Jan, Feb, Mar, Apr…}
MonthGenitiveNames               : {January, February, March, April…}

Current Culture en-US

The following code works well, because the month shortnames are ‘en-US’ or ‘en-GB’ formatted.

@('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec') | ForEach-Object {
    try{
        Get-Date "$($_)/2023" -f "MM MMM MMMM"
    }catch{
        Write-Warning $($_.Exception.Message)
    }
}

Output:

01 Jan January
02 Feb February
03 Mar March
04 Apr April
05 May May
06 Jun June
07 Jul July
08 Aug August
09 Sep September
10 Oct October
11 Nov November
12 Dec December

de-CH formatted month shortnames can be one of:

The following code runs in an error, because the words ‘mar’ or ‘märz’, ‘okt’ or ‘okt.’, ‘dez’ or ‘dez.’ are not valid DateTime formats for the current culture ‘en-US’ or ‘en-GB’.

@('jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dez') | ForEach-Object {
    try{
        Get-Date "$($_)/2023" -f "MM MMM MMMM"
    }catch{
        Write-Warning $($_.Exception.Message)
    }
}

Output:

01 Jan January
02 Feb February
03 Mar March
04 Apr April
WARNING: Cannot bind parameter 'Date'. Cannot convert value "mai/2023" to type "System.DateTime".
Error: "The string 'mai/2023' was not recognized as a valid DateTime. There is an unknown word starting at index '0'."
06 Jun June
07 Jul July
08 Aug August
09 Sep September
WARNING: Cannot bind parameter 'Date'. Cannot convert value "okt/2023" to type "System.DateTime".
Error: "The string 'okt/2023' was not recognized as a valid DateTime. There is an unknown word starting at index '0'."
11 Nov November
WARNING: Cannot bind parameter 'Date'. Cannot convert value "dez/2023" to type "System.DateTime".
Error: "The string 'dez/2023' was not recognized as a valid DateTime. There is an unknown word starting at index '0'."

Current Culture de-CH

Some of the Tools in Switzerland creates this ‘de-CH’ formatted month shortnames in the PDF-Reports of Abacus or SAP.
Change the current culture for this thread to ‘de-CH’, that we can calculate with the month shortnames as DateTime:

if(($CurrentCulture).Name -notmatch 'de-CH'){
    [System.Threading.Thread]::CurrentThread.CurrentCulture = "de-CH"
    @('jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dez') | ForEach-Object {
        try{
            Get-Date "$($_)/2023" -f "MM MMM MMMM"
        }catch{
            Write-Warning $($_.Exception.Message)
        }
    }
}

Output:

01 Jan Januar
02 Feb Februar
03 Mär März
04 Apr April
05 Mai Mai
06 Jun Juni
07 Jul Juli
08 Aug August
09 Sep September
10 Okt Oktober
11 Nov November
12 Dez Dezember

See also

Get-Date on Microsoft Docs.

[ Top ] [ Blog ]