PowerShell Date Time

To play with Date and Time with PowerShell, the main Cmdlet to use is Get-Date.

TechNet: https://technet.microsoft.com/en-us/library/hh849887.aspx

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. It can format the date and time in several Windows and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.

 

# Get the current date/time
$CurrentDateTime = Get-Date
Write-Host "Current date/time is : $CurrentDateTime"
Write-Host ""


# Get the current date only
$CurrentDate = $CurrentDateTime.ToShortDateString()
Write-Host "Current date is : $CurrentDate"
Write-Host ""


# Get the current time only
$CurrentTime = $CurrentDateTime.ToShortTimeString()
Write-Host "Current time is : $CurrentTime"
Write-Host ""


# Generate current time + 4 hours
$CurrentDateTimePlus4h = $CurrentDateTime.AddHours(4)
$CurrentTimePlus4h = $CurrentDateTimePlus4h.ToShortTimeString()
Write-Host "In 4 hours, time will be : $CurrentTimePlus4h" 
Write-Host ""


# Set a valid custom date and check
$CustomDate1 = "20.09.1980"
Write-Host "1st customized date : $CustomDate1"
If ($CustomDate1 -as [DateTime]) {
    Write-Host "1st customized date valid"
    Write-Host ""
}
Else {
    Write-Host "1st customized date not valid"
    Write-Host ""
}


# Set a non-valid custom date and check
$CustomDate2 = "31.09.2016"
Write-Host "2nd customized date : $CustomDate2"
If ($CustomDate2 -as [DateTime]) {
    Write-Host "2nd customized date valid"
    Write-Host ""
}
Else {
    Write-Host "2nd customized date not valid"
    Write-Host ""
}


# Set a valid custom time and check
$CustomTime1 = "15:30"
Write-Host "1st customized time : $CustomTime1"
If ($CustomTime1 -as [DateTime]) {
    Write-Host "1st customized time valid"
    Write-Host ""
}
Else {
    Write-Host "1st customized time not valid"
    Write-Host ""
}


# Set a non-valid custom time and check
$CustomTime2 = "08:62"
Write-Host "2nd customized time : $CustomTime2"
If ($CustomTime2 -as [DateTime]) {
    Write-Host "2nd customized time valid"
    Write-Host ""
}
Else {
    Write-Host "2nd customized time not valid"
    Write-Host ""
}


# Convert time from hh:mm to AM/PM
$CustomTime3 = "06:45"
Write-Host "3rd customized time : $CustomTime3"
$CustomTime3AMPM = Get-Date $CustomTime3 -format t
Write-Host "3rd customized time formated AM/PM : $CustomTime3AMPM"
Write-Host ""


# Parse a date
$CustomDate3 = "01.09.2013"
Write-Host "3rd customized date : $CustomDate3"
$CustomDate3 = $CustomDate3.Split(".")
$CustomYear3 = $CustomDate3[2]
Write-Host "Year : $CustomYear3"
$CustomMonth3 = $CustomDate3[1]
Write-Host "Month : $CustomMonth3"
$CustomDay3 = $CustomDate3[0]
Write-Host "Day : $CustomDay3"
Write-Host ""