PowerTip: Convert String into DateTime Object


Summary: Use Windows PowerShell to convert a string into a DateTime object.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily create a System.DateTime object from a string?

Hey, Scripting Guy! Answer Use the [DateTime] type accelerator to convert the string, for example:

[datetime]"1/2/14"

Comments (12)

  1. Chris J Warwick says:

    Beware. THIS IS BROKEN. [DateTime] assumes US format dates. As a user outside of the US, the date in the example above would be the 1st February 2014 – but I assume not everyone would see it that way. This does not vary depending on your locale.

    Very sadly, the PowerShell team got this horribly, horribly wrong between the Monad beta and the release of PowerShell v1.0 – and now it’s unfortunately much too late to change it.

    They should have read RFC3339 (http://tools.ietf.org/html/rfc3339) or ISO 8601 (http://www.iso.org/iso/catalogue_detail?csnumber=40874 or
    http://en.wikipedia.org/wiki/ISO_8601) upon which the RFC is based. A sad example of parochialism that is thankfully otherwise absent in the product.

    Because of this, as Mike Shepard has noted, you’re much better off using Get-Date, which will parse date strings according to your local conventions.

    🙁

  2. Anonymous says:

    Chris, your so right!

    The last few days I finished a script for cleaning up expired certificates from a CA database and there I created a "Validatepattern" Regular Expression filter for the date Parameter for different formats.

    Here in Switzerland we use 20.12.2014 in other countries 12/20/2014 => different order / different Separators! No Standard and so everything is getting complicated!

    Here is the link to my script for CA maintenance added to the scriptcenter:
    https://gallery.technet.microsoft.com/scriptcenter/Script-to-delete-expired-8fcfcf48

  3. Chris J Warwick says:

    I’ve raised a bug on Connect. Please vote if you agree:

    https://connect.microsoft.com/PowerShell/feedback/details/1062130

  4. Chris J Warwick says:

    @Dates:

    [DateTime] may honour culture in some senses, but it assumes that short format date strings (such as those found in many log files for example) are in US format (i.e. mm/dd/yy). This wasn’t always so. In the Monad betas the string format was assumed to be country
    specific; but just before V1.0 a decision was taken that [DateTime] should use a fixed format – the argument (spurious in my opinion) being that this was necessary for portability.

    On my system:

    PS:> Get-Culture | Format-List Name, DisplayName, EnglishName

    Name : en-GB
    DisplayName : English (United Kingdom)
    EnglishName : English (United Kingdom)

    PS:> Get-Culture | Select -Expand DateTimeFormat | Select ShortDatePattern

    ShortDatePattern —————-
    dd/MM/yyyy

    PS:> [DateTime]’12/21/2014′

    21 December 2014 00:00:00

    PS:> [DateTime]’21/12/2014′

    Cannot convert value "21/12/2014" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
    At line:1 char:1
    + [DateTime]’21/12/2014′
    + ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

    PS:>

    I have two reasons for stating that this is broken in my opinion:
    1. [DateTime] should, like Get-Date, respect culture, and
    2. If a fixed format date must be used it should be in an internationally agreed format (ISO 8601/RFC3339) as mentioned previously.

    They could fix this by introducing to new two accelerators:

    [IsoDateTime]

    and

    [LocalDateTime]

    …and subsequently deprecating [DateTime]

  5. Mike Shepard says:

    I would have used get-date "1/2/14"

  6. Dates says:

    [datetime] understands most formats and honors culture. It may display oddly but, if used as an object, it is correct. Don’t mistake presentation for actual value. The date is correct for you timezone.

    You can enter dates in local format and they will be interpreted correctly.

    Check here to check that you have you datetime formats set correctly. If you are in Europe and are using a US version of Windows this may not get set up correctly you may need to adjust Windows.

    Get-Culture|select -expand datetimeformat

    If you are in Europe (ornotin US) and use a US format for input it will be incorrect. You can always use a full date expression to get it right.

    [datetime]’1 Feb 2014′
    [datetime]’Feb 1 2014′
    [datetime]’1 February 2014′
    [datetime]’February 1 2014′

    All work in any culture short of East Asia I believe.

    See: ([datetime]0)|gm

  7. BrianS says:

    I’m very surprised and disappointed there are so many inconsistencies in Power$Hell

  8. Johnny C/@proveisso says:

    when I read the post I thought: WOW, that easy? Then I read the comments and… wow, all those problems? O.o so I tried the "Get-Culture|select -expand datetimeformat" that Dates mentioned: "ShortDatePattern: dd/MM/yyyy" and here I thought, okay, no problem
    then.

    But then….

    PS C:Usersmyuser> get-date 01/05/2015
    sexta-feira, 1 de maio de 2015 00:00:00
    PS C:Usersmyuser> [datetime]"01/05/2015"
    segunda-feira, 5 de janeiro de 2015 00:00:00

    So, if I use "get-date" it DO understand exactly which date I wanted it to, but if I try the second method, it changes dd/MM to MM/dd?! Geez…

  9. Ed Kovac says:

    the most elegant solution that i’ve found is:
    (new-object System.DateTime 2015, 11, 19)
    to create a date passing the year, then month, then day.
    Hours, minutes & seconds may also be added:
    (new-object System.DateTime 2015, 11, 19, 12, 13, 14)
    And milliseconds may also be addad after those too:
    (new-object System.DateTime 2015, 11, 19, 12, 13, 14, 987)

  10. rewt says:

    datetime time only

  11. For non-US DateTime formats, conversion can be achieved this way :
    function Convert-StringToDateTime
    {
    param
    (
    [Parameter(Mandatory = $true)]
    [String] $DateTimeStr
    )

    $DateFormatParts = (Get-Culture).DateTimeFormat.ShortDatePattern -split ‘/|-|\.’

    $Month_Index = ($DateFormatParts | Select-String -Pattern ‘M’).LineNumber – 1
    $Day_Index = ($DateFormatParts | Select-String -Pattern ‘d’).LineNumber – 1
    $Year_Index = ($DateFormatParts | Select-String -Pattern ‘y’).LineNumber – 1

    $DateTimeParts = $DateTimeStr -split ‘/|-|\.| ‘

    $DateTimeParts_LastIndex = $DateTimeParts.Count – 1

    $DateTime = [DateTime] $($DateTimeParts[$Month_Index] + ‘/’ + $DateTimeParts[$Day_Index] + ‘/’ + $DateTimeParts[$Year_Index] + ‘ ‘ + $DateTimeParts[3..$DateTimeParts_LastIndex] -join ‘ ‘)

    return $DateTime
    }

    # Convert French DateTime string To DateTime object
    $DateTime = Convert-StringToDateTime “10/03/2016 23:00”

Skip to main content