简体   繁体   中英

Apply UFormat to System.DateTime variable

I am trying to apply a specific format to a DateTime variable on Powershell, but I am finding it impossible.

This works fine:

>> Get-Time -UFormat "%Y%m%d-%h%M%S"
20210412-135938

But if I try to assign it to a variable and then do the formatting, I encounter an error, for example

 $startDate=Get-Date -Year 2021 -Month 01 -Day 01 -Hour 11 -Minute 00 -Second 00
 $startDate=$startDate.addHours(10)
 $startDate=$startDate.addHours(23)
 ($startDate) -UFormat "%Y%m%d-%h%M%S"

Then I get an Token Uformat unexpected error. Could someone throw some light as on how to get this formatting to work?

Thank you,

You can pass an existing [datetime] value to Get-Date 's -Date parameter:

Get-Date -Date $startDate -UFormat "%Y%m%d-%h%M%S"

There are more ways of formatting a date that are more 'PowerShelly' then using UFormat:

  1. use the.Net ToString() method:
(Get-Date).AddHours(10).ToString("yyyyMMdd-HHmmss")
  1. use the -Format parameter of Get-Date :
$startDate = (Get-Date).AddHours(10)
Get-Date -Date $startDate -Format "yyyyMMdd-HHmmss"
  1. or use the -f format operator:
'{0:yyyyMMdd-HHmmss}' -f (Get-Date).AddHours(10)

-UFormat switch belongs to the Get-Date commandlet. So you would use this syntax:

Get-Date ($startDate) -UFormat "%Y%m%d" for example.

And if I am interpreting what you "really" want in your date format string, you have incorrect case on the hour token.

"%Y%m%d-%h%M%S" Should be

Get-Date ($startDate) -UFormat %Y%m%d-%H%M%S

Which will return: 20210102-200000

These tokens - at least where I get them - are from TCL.

Goggle tcl clock manual page for a complete list.

I usually use -UFormat switch - I know TCL tokens and don't have to worry about escaping letters used in Microsoft date string tokens.

Get-Date ($startDate) -Format "Hello-yyyyMMdd-HHmmss-World"

returns: 20ello-20210102-200000-Worl2 because the H and d are tokens - and would need to be escaped \H \d

whereas

Get-Date ($startDate) -UFormat "Hello-%Y%m%d-%H%M%S-World"

returns: Hello-20210102-200000-World

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