Home > Software engineering >  Change the date order of a txt file
Change the date order of a txt file

Time:11-01

I have a variable where I dump the day, month and year of some events.

$Myvariable -> 17/10/2022

I need to change the order of the day and month.

$NewVariable-> 10/17/2022

Would someone know how to do it? Any ideas?

I'm starting to work with powershell and I can't think of a way to do it.Any help or suggestion is welcome.

Thanks for your time

CodePudding user response:

In Powershell

$NewVariable = '{0:MM/dd/yyyy}' -f [datetime]::ParseExact($MyVariable, 'dd/MM/yyyy',$null)

If your current Regional Settings dictate hyphens instead of slashes in the output format (like on my machine which has Dutch settings), you might want to change '{0:MM/dd/yyyy}' into '{0:MM\/dd\/yyyy}'. By prefixing the slashes with backslashes, you will effectively escape them so the output is always like 10/17/2022.

CodePudding user response:

To add to Theo's helpful answer:

A solution based on text manipulation, using the -split and -join operators, combined with array indexing:

$MyVariable = '17/10/2022'

# -> '10/17/2022'
$NewVariable =
  ($MyVariable -split '/')[1, 0, 2] -join '/'

A solution based on [datetime] objects, as in Theo's answer:

$MyVariable = '17/10/2022'

# -> '10/17/2022'
$NewVariable =
  [datetime]::Parse($MyVariable, [cultureinfo] 'en-GB').ToString('MM"/"dd"/"yyyy')

Working with [datetime] objects gives you much more flexibility, if needed:

  • The solution takes advantage of the fact that 17/10/2022, i.e. a day-first date format with / separators, is used in the en-GB (UK-English) culture, and therefore can be parsed as-is in the context of that culture. The resulting [datetime] instance is then formatted as needed, using the .ToString() method.

  • If your current culture is the US-English culture, you can simplify to .ToString('d'), because 10/17/2022 is that culture's short date format (d).

CodePudding user response:

Here's a bash answer:

Myvariable='17/10/2022'

Newvariable=$( awk -F/ '{ printf("%s/%s/%s",$2,$1,$3) }' <<< "$Myvariable" )

echo $Newvariable

Results:

10/17/2022
  • Related