Thursday, May 7, 2015

#66 : Formatted Date and Time Output

Mostly, in course of scripting, we need to display date and time in a qualified format. The format depends on the requirement suggested. Such as, your script log will have timestamp in a format like LOG_201505150732.log, but inside log, you timestamp might be set as 2015-05-15 07:32:03. Based on purpose, we use time in different ways.

Powershell does not require much more effort in playing with format. It is more straight forward than anything in Powershell. Simply, remember the table below to set the format :

SpecifierTypeExample Example Output
ddDay{0:dd}10
dddDay name{0:ddd}Tue
ddddFull day name{0:dddd}Tuesday
f, ff, …Second fractions{0:fff}932
gg, …Era{0:gg}A.D.
hh2 digit hour{0:hh}10
HH2 digit hour, 24hr format{0:HH}22
mmMinute 00-59{0:mm}38
MMMonth 01-12{0:MM}12
MMMMonth abbreviation{0:MMM}Dec
MMMMFull month name{0:MMMM}December
ssSeconds 00-59{0:ss}46
ttAM or PM{0:tt}PM
yyYear, 2 digits{0:yy}02
yyyyYear{0:yyyy}2002
zzTimezone offset, 2 digits{0:zz}-05
zzzFull timezone offset{0:zzz}-05:00
:Separator{0:hh:mm:ss}10:43:20
/Separator{0:dd/MM/yyyy}10/12/2002


Using toString() function, you can do all kinds of formatting you want.

For example, if you have to get the timestamp for a log file, use below :
$FILE_NAME="ABC_$($(get-date).toString("yyyyMMddhhmmss")).log"

If you want to output the time in log file, it must be little more readable. Such as below :
$MSG="$($(get-date).toString("yyyy/MM/dd HH:mm:ss" )) : Program Started"

There are lot many experiments possible with it. This is simple, yet effective way to handle time.
Enjoy scripting!!
 

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...