Categories

Date and Time

I recently came across a script that used date and time information in this manner

001
002
003
004
005
006
$stuff =  "Stuff"
$monthday = Get-Date -Format "ddMMM"
$year = Get-Date -Format yyyy
$time = Get-Date -Format "HH:mm:ss"
$data = "$monthday" + "," + "$year" + "," + "$time" + "," + "$stuff"
$data

 

This gives a result of

12Oct,2009,15:20:32,Stuff

I didn’t like the way get-date was used three times – its messy .  In most cases it won’t make much difference but if the script runs across a day boundary you just might get some odd results.

The same results can be achieved with

001
002
003
004
$stuff =  "Stuff"
$date = Get-Date
$data = "{0:dd}{1:MMM},{2:yyyy},{3:HH}:{4:mm}:{5:ss},$stuff" -f $date, $date, $date, $date, $date, $date
$data

 

which will give a result of

12Oct,2009,15:20:38,Stuff

The time differences are related to me clicking across different tabs in ISE

In this way we only call Get-date once and use the .NET string formatting to give the results we want.  Much neater and we don’t need to worry about time or date boundaries

 

Technorati Tags: ,,,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>