Search code examples
powershelldatetimestamplogfile

convert Fri Nov 02 14:37:02 2018 to 2018-11-02 14:37:02


I want to convert Fri Nov 02 14:37:02 2018 to 2018-11-02 14:37:02 in Windows Powershell, thanks for any proposals.


Solution

  • here's how to convert a time string to a datetime object & back again ... [grin]

    $TimeString = 'Fri Nov 02 14:37:02 2018'
    $TimeObject = Get-Date -Date '2018-11-02 14:37:02'
    
    'String       = {0}' -f $TimeString
    # convert the above string to a datetime object
    $TS_DateTimeObject = [datetime]::ParseExact('Fri Nov 02 14:37:02 2018', 'ddd MMM dd HH:mm:ss yyyy', $Null)
    
    # my PC locale is set to use yyyy-MM-dd hh:mm:ss as the datetime format
    #    most stateside PC locale setting will be MM-dd-yyyy
    'Object       = {0}' -f $TimeObject
    'TS_Object    = {0}' -f $TS_DateTimeObject
    
    # convert a datetime object to a string
    'DT to String = {0}' -f $TimeObject.ToString('yyyy-MM-dd HH:mm:ss')
    

    output ...

    String       = Fri Nov 02 14:37:02 2018
    Object       = 2018-11-02 2:37:02 PM
    TS_Object    = 2018-11-02 2:37:02 PM
    DT to String = 2018-11-02 14:37:02
    

    here is a link to the datetime format codes ...

    Date and Time formats - PowerShell - SS64.com
    https://ss64.com/ps/syntax-dateformats.html