Subtract or Add Days, Months or Year to Dates with Custom Date Pattern using PowerShell Script

Wednesday, August 6, 2014

I will share a simple trick for adding days or months to dates and the result will be a custom date pattern. Check the script below… 



If you want to add and subtract Months or Days on current date:

$currentAddYears = [DateTime]::Now.AddYears(2)
$currentAddMonths = [DateTime]::Now.AddMonths(2)
$currentAddDays = [DateTime]::Now.AddDays(14)

$currentSubtractYears = [DateTime]::Now.AddYears(2)
$currentSubtractMonths = [DateTime]::Now.AddMonths(-2)
$currentSubtractDays = [DateTime]::Now.AddDays(-14)


Results will be:

8/6/2014 2:23:00 PM    #now

8/6/2016 2:23:00 PM   #$currentAddYears
10/6/2014 2:23:00 PM  #$currentAddMonths
8/20/2014 2:23:00 PM   #$currentAddDays

8/6/2012 2:23:00 PM   #$currentSubtractYears
6/6/2014 2:23:00 PM   #$currentSubtractMonths
7/23/2014 2:23:00 PM   #$currentSubtractDays


Now if you want to change the results to custom format, you can use  –format of Get-Date.

$format1 = Get-Date $currentAddMonths -format "MMMM yyyy"
$format2 = Get-Date $ currentAddDays -format "MMMM dd, yyyy"

Results will be:

October 2014      #$format1

August 20, 2014  #$format2


These are methods available in adding dates.

·        AddDays
·        AddHours
·        AddMilliseconds
·        AddMinutes
·        AddMonths
·        AddSeconds
·        AddTicks
·        AddYears


These are some common custom format in dates: (case sensitive)

Specifier
Description
d
Day of the month. Single digit, without leading zero (1)
dd
The day of the month. Single-digit days will have a leading zero. (01)
ddd
The abbreviated name of the day of the week. (Wed)
dddd
The full name of the day of the week (Wednesday)
mm
The minute. Single-digit minutes will have a leading zero.
M
Numeric month. Single digit, without leading zero (8) -August
MM
Numeric month. Single digit, with leading zero (08) -August
MMM
The abbreviated name of the month (Aug)
MMMM
The full name of the month (August)







Choose a platform and click the tab to comment :)
0 Comments
Disqus
Fb Comments
Comments :

No comments:

Post a Comment