pburgh
pburgh

Reputation: 461

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

How does one get date-1 and format it to mm-dd-yyyy in PowerShell?

Example: If today is November 1, 2013, and I need 10-31-2013 in my code.

I've used AddDays(-1) before, but I can't seem to get it to work with any formatting options.

Upvotes: 35

Views: 141714

Answers (5)

Ludo
Ludo

Reputation: 1

This is the most simple solution for me:

  • just the current date:

    $tStamp = Get-Date -format yyyy_MM_dd_HHmmss
    
  • current date with some months added:

    $tStamp = Get-Date (get-date).AddMonths(6).Date -Format yyyyMMdd
    

Upvotes: 0

Romylussone
Romylussone

Reputation: 815

Using system reference :

 [System.DateTime]::Now.AddDays(-1).ToString('MM-dd-yyyy')

Upvotes: 0

Salman
Salman

Reputation: 9

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

Upvotes: -1

marcus
marcus

Reputation: 171

I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:

Get-Date (Get-Date).AddDays(-1) -format D

Upvotes: 15

mjolinor
mjolinor

Reputation: 68273

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

Upvotes: 82

Related Questions