Serializing Date and Time in a Culture-Invariant Way

When you save date and time to text, for example when exporting to CSV, or when creating text reports, DateTime objects are converted to the date and time format defined in your regional settings:

 
PS> $date = Get-Date -Date '2017-02-03 19:22:11'

PS> "$date"
02/03/2017 19:22:11

PS> $date.ToString()
03.02.2017 19:22:11

PS> Get-Date -Date $date -DisplayHint DateTime

Freitag, 3. Februar 2017 19:22:11
 

These all are culture-dependent formats, so when someone else opens your data, conversion back to a real datetime may fail. This is why it is recommended to convert datetime information to the culture-independent ISO format whenever you are saving it as text:

 
PS> Get-Date -Date $date -Format 'yyyy-MM-dd HH:mm:ss'
2017-02-03 19:22:11

PS>
 

The ISO format always correctly converts back to a DateTime object, no matter what language your computer is using:

 
PS> [DateTime]'2017-02-03 19:22:11'

Friday, February 3, 2017 19:22:11
 

In addition, it is designed in a way that sorts correctly using alphanumeric sort.

Twitter This Tip! ReTweet this Tip!