1

I'm passing a string that represents a date i.e. 20180625 to my Powershell script.

I'm then taking the string parameter, which is called $currentDate and formatting it as follows:

$date = [datetime]::ParseExact($currentDate,"yyyyMMdd",$null)

However, when I write the $date variable out it's displaying as 6/29/2018 12:00:00 AM.

I'm doing this because I need to get the day of the year for my script:

$dayofyear = ($date).dayofyear

Which works. I just expected the $date to be in the yyyyMMdd format. Just curious as to why this is happening.

2 Answers 2

3

The format parameter for ParseExact tells the parser what format the date you are giving it is in. The object you get back is a DateTime object not a string. To get the string in the format that you want, use the .ToString() method then give if the format that you want the string to be in.

As an example:

$currentDate = '20180629'
$date = [datetime]::ParseExact($currentDate,"yyyyMMdd",$null)
$dayOfYear = $date.DayOfYear
$date.ToString('yyyyMMdd')
Sign up to request clarification or add additional context in comments.

Comments

0

$date is an object of type [datetime] which contains an exact measure of time in ticks. For instance, a timespan of 1 day would be 864000000000 ticks. Thus it is not possible to have $null values in a lesser field (864 ticks would only be a few milliseconds). $date prints to the console with a default formatting, which can be changed. However, since each field down to -Milliseconds is populated as 0, when that default format does contain fields such as -hours, they will be displayed as the minimum value (in this case, 12am exactly).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.