简体   繁体   中英

Powershell - amend date format to values in CSV column

I'm looking for a PowerShell script for the following ...

I have a CSV spread sheet which automatically downloads from a website, the 2nd column of the spread sheet is a date value in the UK format dd/mm/yyyy. I'd like a script that will change the date format of all values in column 2 to the US date format yyyy/mm/dd.

I'm importing the CSV into a MySQL database using LOAD DATA INFILE and at present the dates are going in 2017/02/15 when they should be 2015/02/17.

An example of the CSV file format is as follows ...

Col1,Col2,Col3,Col4
Value1,17/02/15,Value3,Value4
Value1,18/02/15,Value3,Value4
Value1,19/02/15,Value3,Value4

I need it to become ...

Col1,Col2,Col3,Col4
Value1,2015-02-17,Value3,Value4
Value1,2015-02-18,Value3,Value4
Value1,2015-02-19,Value3,Value4

one way could be (will replace all date in UK format to US format, regardless of the column):

(get-content c:\file.csv) -replace "(\d{2})\/(\d{2})\/(\d{4})", '$3/$2/$1'  

if you want to save the result pipe to set-content :

(get-content c:\file.csv) -replace "(\d{2})\/(\d{2})\/(\d{4})", '$3/$2/$1'  |sc c:\file.csv 

I like to use TryParseExact . You can convert many formats and you can find invalid values.

Example:

$dateString = "17/02/2015"

$format = "dd/MM/yyyy"
[ref]$parsedDate = get-date
$parsed = [DateTime]::TryParseExact($dateString, $format,[System.Globalization.CultureInfo]::InvariantCulture,[System.Globalization.DateTimeStyles]::None,$parseddate)

$parsedDate.Value.ToString("yyyy/MM/dd")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM