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 :
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!!
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 :
Specifier | Type | Example | Example Output |
dd | Day | {0:dd} | 10 |
ddd | Day name | {0:ddd} | Tue |
dddd | Full day name | {0:dddd} | Tuesday |
f, ff, … | Second fractions | {0:fff} | 932 |
gg, … | Era | {0:gg} | A.D. |
hh | 2 digit hour | {0:hh} | 10 |
HH | 2 digit hour, 24hr format | {0:HH} | 22 |
mm | Minute 00-59 | {0:mm} | 38 |
MM | Month 01-12 | {0:MM} | 12 |
MMM | Month abbreviation | {0:MMM} | Dec |
MMMM | Full month name | {0:MMMM} | December |
ss | Seconds 00-59 | {0:ss} | 46 |
tt | AM or PM | {0:tt} | PM |
yy | Year, 2 digits | {0:yy} | 02 |
yyyy | Year | {0:yyyy} | 2002 |
zz | Timezone offset, 2 digits | {0:zz} | -05 |
zzz | Full 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