Thursday, March 26, 2009

Showing the Date and Time in .Net

I like the concept of master pages, they seem sort of like includes on steroids. In Classic ASP, I would build my template and use includes for those items that would be global to the site: header, footer, navigation, etc. master pages in .Net let you do the same sort of thing.

So I get my master page created and I want to put the copyright notice on the footer. But how to dynamically insert the year?
d, day of month: System.DateTime.Now.ToString(" d") // can't use just "d"
dd, zero-padded day of month: System.DateTime.Now.ToString("dd")
ddd, abbreviated day of week: System.DateTime.Now.ToString("ddd")
dddd, full day of week: System.DateTime.Now.ToString("dddd")
h, hour: System.DateTime.Now.ToString(" h") // can't use just "h"
hh, hour, zero padded: System.DateTime.Now.ToString("hh")
H, hour, 24-hr: System.DateTime.Now.ToString(" H") // can't use just "H"
H, hour, 24-hr, zero padded: System.DateTime.Now.ToString("HH")
m, minute: System.DateTime.Now.ToString(" m") // can't use just "m"
M, month: System.DateTime.Now.ToString(" M") // can't use just "M"
MM, month, zero padded: System.DateTime.Now.ToString("MM")
MMM, month abbreviated: System.DateTime.Now.ToString("MMM")
MMMM, month full name: System.DateTime.Now.ToString("MMMM")
y, year (omits century): System.DateTime.Now.ToString(" y") // can't use just "y"
yy, 2-digit year, zero padded: System.DateTime.Now.ToString("yy")
yyyy, 4-digit year, zero padded: System.DateTime.Now.ToString("yyyy")
So to actually use this in a page, you'd do:
Copyright <%= System.DateTime.Now.ToString("yyyy") %> 
This will write the full four-digit year.

Here's a full list of all the Date and Time formats.

No comments: