Home > Software engineering >  Getting Date into UK time format correctly before writing to CSV - powershell
Getting Date into UK time format correctly before writing to CSV - powershell

Time:08-05

I have a small bit of code that calculates days elapsed of a computers login. It works fine and gives me the correct information. But when the strings are put into the CSV file it displays the date in US time format: MM/dd/yyyy HH:mm:ss but I want UK: dd/MM/yyyy HH:mm:ss returned to the CSV.

This is the code that gives me the information I need:
Note: The date format in ps displays like this: 04 August 2022 11:21:40

##get date into variable
$Date = Get-Date
#Get pc login timestamp into variable
$lastlogon = $Computer.lastlogonTimestamp
##Calculate the days elapsed but this part is really irrelevant for the question.  
$dayslogonelapsed = $Date - $lastlogon

Once I am ready to write data to the csv file the code is as follows:

$csvdescriptoutput = 'C:\temp\csvtest.csv'
###Log data to a single variable for CSV. 
$logline = ("$lastlogon;"   "$($dayslogonelapsed.Days)")
###write to CSV
Add-Content -Path $csvdescriptoutput -Value $LogLine   

When the data is in the log file it displays like this: 07/24/2022 14:07:28 - US format. When I need this: 24/07/2022 14:07:28 - UK format. My PC is set to UK time locals and so is my Excel.

Also changing it excel once in the sheet is not an option because the CSV is only looking at strings.

CodePudding user response:

Pass a custom format string to Get-Date like this:

$Date = Get-Date -Format 'dd\/MM\/yyyy HH\:mm\:ss'

This turns the date into a string. To keep $Date as a [DateTime], you can also format it on-demand using its ToString() method:

$Date = Get-Date 
$Date.ToString('dd\/MM\/yyyy HH\:mm\:ss')

Note:

In order to ensure that the reserved characters / and : are interpreted literally, independent of locale, escape them by putting a backslash in front of them.

More info on reserved characters and escaping.

  • Related